Home  >  Article  >  Backend Development  >  PHP magic method __isset __unset (3), __isset__unset_PHP tutorial

PHP magic method __isset __unset (3), __isset__unset_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:13:19996browse

PHP magic method __isset __unset (3), __isset__unset

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>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/916822.htmlTechArticlePHP magic method __isset __unset (3), __isset__unset Slowly looking for the night, the bright moon hangs high in the sky __isset() - When using the isset() method on class attributes or non-class attributes, if there is no or...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn