Home > php教程 > php手册 > PHP 魔术方法 __isset __unset (三),__isset__unset

PHP 魔术方法 __isset __unset (三),__isset__unset

WBOY
Release: 2016-06-13 09:20:23
Original
937 people have browsed it

PHP 魔术方法 __isset __unset (三),__isset__unset

慢慢长寻夜,明月高空挂

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

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

<?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";
Copy after login

结果如下:

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>
Copy after login

 

Related labels:
php
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template