PHP魔术方法__ISSET、__UNSET使用实例

WBOY
Release: 2016-06-06 11:21:07
Original
1027 people have browsed it

__isset()    – 在对类中属性或者非类中属性使用isset()方法的时候如果没有或者非公有属性,则自动执行__isset()的方法

__unset()  - 在对类中属性或者非类中属性使用unset()方法的时候如果没有或者非公有属性,则自动执行__unset()的方法

代码如下:


    /**
     * 针对类中的魔术方法 __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 '

';<br>
var_dump(isset($exa->public));<br>
echo "\n";<br>
var_dump(isset($exa->protected));<br>
echo "\n";<br>
var_dump(isset($exa->private));<br>
echo "\n";<br>
var_dump(isset($exa->noVar));<br>
echo "\n";<br>
echo '<hr>';
<p><br>
unset($exa->public);<br>
var_dump($exa);</p>
<p>echo "\n";<br>
unset($exa->protected);<br>
echo "\n";<br>
unset($exa->private);<br>
echo "\n";<br>
unset($exa->noVar);<br>
echo "\n";<br>
</p>
<p>结果如下:</p>
<p>bool(true)</p>
<p>这里通过__isset()方法查看属性名为 protected</p>
<p>bool(false)</p>
<p>这里通过__isset()方法查看属性名为 private</p>
<p>bool(false)</p>
<p>这里通过__isset()方法查看属性名为 noVar</p>
<p>bool(false)<br>
</p><p class="codetitle"> 代码如下:</p><p class="codebody" id="code75579"><br>
object(Example)#1 (2) {<br>
  ["protected:protected"]=><br>
  string(3) "pro"<br>
  ["private:private"]=><br>
  string(3) "pri"<br>
}<br>
</p>
<p>这里通过__unset()方法要销毁属性名为 protected</p>
<p>这里通过__unset()方法要销毁属性名为 private</p>
<p>这里通过__unset()方法要销毁属性名为 noVar</p>
    
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!