PHP magic method_PHP tutorial

WBOY
Release: 2016-07-13 09:48:02
Original
970 people have browsed it

PHP’s magic method

1. __get/__set: taking over object attributes
2. __call/__callStatic: Control the use of php object methods
3. __toString: Convert php object into string
4. __invoke: Call this method when executing a php object as a function

<code>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;
    }
}
</code>
Copy after login

$Obj = new Object();

$Obj->title = "Hello";//When assigning a value to an object that does not exist, it will automatically call the __set method

echo $Obj->title;//When reading an attribute that does not exist in an object, it will automatically call the __get method

echo $Obj->test("hello","123"); //When calling a method that does not exist on an object, the __call method will be automatically called

echo $Obj::test1("hello1","1234"); //When calling a static method that does not exist in the object, the __callStatic method will be automatically called

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

echo $Obj(“hello”);//When an object is used as a function, the __invoke method will be automatically called

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1025012.htmlTechArticlePHP’s magic method 1. __get/__set: Take over the object attributes 2. __call/__callStatic: Control the php object Use of methods 3. __toString: Convert php objects into strings 4. __invoke:...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template