柳周侯爷

柳周侯爷

做好自己做好事
twitter

PHP Magic Methods

PHP has many magic methods that are automatically called when triggered. These convenient methods greatly enhance our programming convenience.

__construct(): 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, as almost every object needs to initialize some data.

__destruct(): Automatically called before an object is destroyed, used to clean up resources, such as automatically disconnecting from a database.

__invoke(): Automatically called when an object is invoked as a function. Mainly used to write directly callable classes, closure functions default to implementing __invoke().

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(): Automatically called when accessing a non-existent or private property.

__set(): Automatically called when setting a non-existent or private property.

__call(): Automatically called when calling a non-existent or private method.

__callStatic(): Automatically called when calling a non-existent or private static method.

__toString(): Automatically called when attempting to convert an object to a string.

__clone(): Automatically called when cloning an object, used to copy the object's member variables.

__sleep(): Automatically called when serializing an object, used to return an array of names of all values contained in the instance.

__wakeup(): Automatically called when deserializing an object, used to re-read all values.

__isset(): Automatically called when checking if a non-existent or private property is set.

__unset(): Automatically called when deleting a non-existent or private property.

__set_state(): Automatically called when exporting a class or object using the var_export() function.

__debugInfo(): Automatically called when calling the var_dump() function, used to return the object's debug information.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.