Use of the PHP magic method

Source: Internet
Author: User

1.__Get/__set call these two functions when the class has no properties to access$obj = NewImooc\object ();
$obj -title= "Hello";
Echo$obj -title;

<?php
namespaceImooc;
classObject
{
protected$array= Array();
function__set ($key, $value)
{
Var_dump (__method__);
$this -Array[$key] = $value;
}
function__get ($key)
{
Var_dump (__method__);
return$this -Array[$key];
}
}

2.__Call /__callstaticwhen the class does not have the function called, the two functions are called
$obj = NewImooc\object ();
$obj ->test ("Hello"123);
Echoimooc\object::Test("World", 1233);

<?php
namespaceImooc;
classObject
{
function__call ($func, $param)
{
Var_dump ($func, $param);
returnThe Magic function\ n";
}
static function__callstatic ($func, $param)
{
Var_dump ($func, $param);
returnthe Magic static function\ n";
}
}

3.__toStringCall this function automatically when the object is used as a string
 $obj    =  new  imooc\object () ;
$obj ;

<?php
namespaceImooc;

classObject
{
function__tostring ()
{
return"ToString";
}
}

3.x_InvokewhenThe function is called automatically when the object is used as a function
 $obj    =  new  imooc\object () ;
$obj ("Test1") ;

<?php
namespaceImooc;

classObject
{
function__invoke ($param)
{
Var_dump ($param);
return"Invoke";
}
}


From for notes (Wiz)

Use of the PHP magic method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.