The Magic Method of PHP

Source: Internet
Author: User
Tags array object key return

1. __get/__set: Takeover of object properties
2, __call/__callstatic: Control the use of Php object method
3. __tostring: Convert PHP objects to strings
4, __invoke: A PHP object as a function to the implementation of the method back and forth

class Object
{
 protected $array = array();

    function __set($key,$value)
    {
        var_dump(__METHOD__);
        $this->array[$key] = $value;
    }
    function __get($key)
    {
        var_dump(__METHOD__);
        return $this->array[$key];
    }

    function __call($func,$param)
    {
        var_dump($func,$param);
        return magic mathod __call;
    }

    static function __callStatic($func,$param)
    {
        var_dump($func,$param);
        return magic mathod __callStatic;
    }

    function __toString()
    {
        return __toString;
    }

    function __invoke($param)
    {
        var_dump($param);
        return invoke;
    }
}

$OBJ = new Object ();

$OBJ->title = "Hello";//When you assign a value to a property that does not exist for an object, it automatically invokes the __set method

echo $OBJ->title;//to read a property that does not exist for an object, it automatically invokes the __get method

echo $Obj->test ("Hello", "123"); The __call method is automatically invoked when a method that does not exist for an object is invoked

echo $OBJ:: Test1 ("Hello1", "1234"); The __callstatic method is automatically invoked when a static method that does not exist for an object is invoked

echo $Obj;//When an object is output directly (because the object cannot be output directly), the __tostring method is automatically invoked to convert the object to a string

echo $Obj ("Hello");//When an object is used as a function, the __invoke method is automatically invoked



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.