php 類中的各種攔截器

來源:互聯網
上載者:User

1、__get( $property ) 訪問未定義的屬性時調用

 

 

class lanjie{    function __get($name)    {        echo $name." property not found! ";    }}$ob = new lanjie();echo $ob->g;

當我們調用對象$ob未定義的屬性g時,調用攔截器__get()方法,輸出“g property not found!”;

 

 

 

2、__set( $property , $value ) 給未定義的屬性調用時賦值

 

 

class person{    private $_age;    private $_name;    function __set($name, $value)    {        $method = "set".  ucfirst($name);        echo $method;        if(method_exists($this, $method) )        {            return $this->$method( $value );        }    }        function setName( $name )    {        $this->_name = $name;        if( !is_null($this->_name) )        {            $this->_name = strtoupper($this->_name);        }    }    function setAge( $age )    {        return $this->_age = (int)$age;    }}$p = new person();$p->name = 'bob';print_r( array( $p ) );

這裡我們可以很清楚的看到 , 當給未定義的‘name’賦值時 ,  會調用“__set()”

其他的還有 __call(), __isset() , __unset();

這裡最有用和最常用的的是__call() , 當調用一個為存在的方法時被調用; __isset()是在對一個為定義的屬性使用isset()函數時被調用, __unset是在對未定義的數以使用unset時被調用

 

轉自:http://blog.csdn.net/shuiping567541/article/details/7061258

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.