Home > Article > Backend Development > Examples of using magic methods in PHP
In this article, the editor will give a brief description of the use of magic methods in PHP and the accompanying code. Interested friends can take a look!
What is the "magic method"?
Methods starting with two underscores in PHP, __construct(), __destruct (), __call(), __callStatic(),__get(), __set(), __isset(), __unset ( ), __sleep(), __wakeup(), __toString(), __set_state,() __clone() __autoload(), etc., are called "Magic methods". If you want PHP to call these magic methods, they must first be defined in the class, otherwise PHP will not execute uncreated magic methods.
1.__get __set is called when assigning and reading inaccessible attributes
2.__sleep is called when serializing objects
3.__wakeup is Call
4 when deserializing the object. When serializing the object, you can only serialize the specified attributes and reduce the size after serialization. When you want to store the object string in, for example, memcache , more useful
5. For example, in the following example, I only serialized the data attribute and restricted it in the __sleep function
<?php class Test{ public $name; protected $data=array(); public function __set($name,$value){ $this->data[$name]=$value; } public function __get($name){ if(!isset($this->data[$name])){ return ""; } return $this->data[$name]; } public function __sleep(){ echo "sleep...\r\n"; return array('data'); } public function __wakeup(){ echo "wakeup...\r\n"; } } $test=new Test(); $test->name="我不会被序列化进去"; $test->bbbb="taoshihan"; $testObjectStr=serialize($test); var_dump($testObjectStr); var_dump(unserialize($testObjectStr));
Related tutorials: A complete set of video tutorials on PHP programming from entry to mastery
The above is the detailed content of Examples of using magic methods in PHP. For more information, please follow other related articles on the PHP Chinese website!