Home >Backend Development >PHP Tutorial >PHP magic method_PHP tutorial
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>
$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