Home >Backend Development >PHP Tutorial >Detailed explanation of php magic method, detailed explanation of php magic_PHP tutorial
From PHP 5 and later, classes in PHP can use magic methods. It stipulates that methods starting with two underscores (__) are reserved as magic methods, so it is recommended that function names do not start with __ unless it is to overload an existing magic method. PHP reserves all class methods starting with _ _ (two underscores) as magic methods.
__toString() and __invoke()
public string __toString (void): This method will be automatically called when the object is used as a string. This method must return a string
__invoke(): This method will be automatically called when the object is called as a method.
__call() and __callStatic()
__call(): When the object accesses a method name that does not exist, the __call() method will be automatically called
__callStatic(): When the object accesses a non-existent static method name, the __callStatic() method will be automatically called
Through these two methods, calls with the same method name can be implemented corresponding to different methods
__get() and __set()
When assigning values to inaccessible properties, __set() will be called
When reading the value of an inaccessible attribute, __get() will be called
When reading the value of an inaccessible attribute, __get() will be called
public function __set($name,$value){
echo "Setting the property " . $name ."to value ". $value ."n";
}
}
$obj = new Magic();
$obj->className = 'MagicClass';//Setting the property classNameto value MagicClass
?>
__isset() and __unset()
When isset() or empty() is called on an inaccessible property, __isset() will be called
When unset() is called on an inaccessible property, __unset() will be called
The above is the introduction and examples of 8 PHP object-oriented magic methods. I hope it will be helpful to everyone