php has many magic methods, which are automatically called when triggered. These conveniences can greatly improve our programming efficiency.
__construct(): This method is automatically called when creating a new object, used to initialize the object's member variables. This is perhaps the most commonly used magic method in php because almost every object needs to initialize some data.
__destruct(): This method is automatically called before an object is destroyed, used to clean up resources, such as automatically disconnecting from a database.
__invoke(): This method is automatically called when an object is invoked as a function. It is mainly used to write classes that can be directly called. Closure functions implement __invoke() by default.
class Test{
public $name;
function __construct($name){
$this->name = $name;
}
function __invoke(){
return 'Hello '.$this->name;
}
}
$closure = function($name){
return 'Hello '.$name;
};
$test = new Test('Lisi');
echo $test();//Hello Lisi
echo $closure('Lisi'); //Hello Lisi
echo $closure->__invoke('Zhangsan'); //Hello Zhangsan
__get(): This method is automatically called when accessing a non-existent or private property.
__set(): This method is automatically called when setting a non-existent or private property.
__call(): This method is automatically called when calling a non-existent or private method.
__callStatic(): This method is automatically called when calling a non-existent or private static method.
__toString(): This method is automatically called when attempting to convert an object to a string.
__clone(): This method is automatically called when cloning an object, used to copy the object's member variables.
__sleep(): This method is automatically called when serializing an object, used to return an array of all the values contained in the instance.
__wakeup(): This method is automatically called when deserializing an object, used to re-read all the values.
__isset(): This method is automatically called when checking if a non-existent or private property is set.
__unset(): This method is automatically called when deleting a non-existent or private property.
__set_state(): This method is automatically called when exporting a class or object using the var_export() function.
__debugInfo(): This method is automatically called when calling the var_dump() function, used to return the debugging information of the object.