Slowly 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 results are 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>