Home >Backend Development >PHP Tutorial >PHP magic methods: __isset and __unset
From php5 and later versions, classes can use magic methods. PHP 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 existing magic methods.
The existing magic methods in PHP include __construct, __destruct, __call, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __set_state and __clone.
This articleSlowly looking for the night, the bright moon hangs high in the sky
__isset() - When using the isset() method on a class attribute or a non-class attribute, if there is no or non-public attribute, the __isset() method will be automatically executed.
__unset() -When using the unset() method on a class attribute or a non-class attribute, if there is no or non-public attribute, the __unset() method will be automatically executed
<?php /** * 针对类中的魔术方法 __isset() 和 __unset() 的例子 */ class Example { public $public; protected $protected; private $private; public function __construct(){ $this->public = 'pub'; $this->protected = 'pro'; $this->private = 'pri'; } public function __isset($var){ echo '这里通过__isset()方法查看属性名为 '.$var."\n"; } public function __unset($var){ echo '这里通过__unset()方法要销毁属性名为 '.$var."\n"; } } $exa = new Example; echo '<pre class="brush:php;toolbar:false">'; var_dump(isset($exa->public)); echo "\n"; var_dump(isset($exa->protected)); echo "\n"; var_dump(isset($exa->private)); echo "\n"; var_dump(isset($exa->noVar)); echo "\n"; echo '<hr/>'; unset($exa->public); var_dump($exa); echo "\n"; unset($exa->protected); echo "\n"; unset($exa->private); echo "\n"; unset($exa->noVar); echo "\n";
The result is as follows:
bool(<span>true</span><span>) 这里通过__isset()方法查看属性名为 protected bool(</span><span>false</span><span>) 这里通过__isset()方法查看属性名为 private bool(</span><span>false</span><span>) 这里通过__isset()方法查看属性名为 noVar bool(</span><span>false</span><span>) ------------------------------------------------------------------------------ </span><span>object</span>(Example)#<span>1</span> (<span>2</span><span>) { [</span><span>"</span><span>protected:protected"]=></span> <span>string</span>(<span>3</span>) <span>"</span><span>pro"</span> [<span>"</span><span>private:private"]=></span> <span>string</span>(<span>3</span>) <span>"</span><span>pri"</span> <span>} 这里通过__unset()方法要销毁属性名为 protected 这里通过__unset()方法要销毁属性名为 private 这里通过__unset()方法要销毁属性名为 noVar</span>
The above introduces the PHP magic methods: __isset and __unset, including the content of PHP magic methods. I hope it will be helpful to friends who are interested in PHP tutorials.