__sleep: called automatically when Serialize is called
__wakeup: when Unserialize is called, it is called automatically and can be used to initialize the object.
classa{ Public $var; //Serialize is called when you don't need to save all the data for a large object. Public function__sleep () {Echo' __sleep called '.Php_eol; return Array(' var '); } //Unserialize is called when it is used to initialize objects. Public function__wakeup () {Echo' __wakeup called '.Php_eol; $this-var= ' Test after Wakeup '; }}$a=NewA;Var_dump(Serialize($a));Var_dump(unserialize(Serialize($a)));
#########################################
__sleep called
e:\wamp64\www\test\test.php:142: string (length=24)
__sleep called __wakeup called
e:\wamp64\www\test\test.php:143: Object (A) [2] Public string (length=17) Public ' VAR1 ' = null public ' var2 ' and null
__tostring: Called when a class is converted to a string
class testclass{ public$foo; /* * * The object is converted to a string output * How to respond when a class is treated as a string * @return Mixed */public function __tostring () { return "toString called"; }} Echo New TestClass ();
__construct: The class of the constructor calls this method each time a new object is created, typically for dynamic injection properties. If a constructor is defined in a subclass, the constructor of its parent class is not implicitly called. To execute the constructor of the parent class, you need to call parent::__construct ()in the constructor of the child class. If a subclass does not have a constructor defined, it inherits from the parent class as if it were a normal class method
__destruct: The destructor executes when all references to an object are deleted or when an object is explicitly destroyed. As with constructors, the destructor of the parent class is not called by the engine. To execute a destructor for a parent class, you must explicitly call parent::__destruct () in the destructor body of the subclass. Also, as with constructors, subclasses inherit the parent class if they do not have a destructor defined by themselves.
class Mydestructableclass { function __construct () { print "in constructor\n" ; $this->name = "Mydestructableclass"; } function __destruct () { print$this->name. "\ n"; }} $obj New Mydestructableclass ();
PHP Magic Method