php 的攔截器執行個體程式碼分析

來源:互聯網
上載者:User
PHP中提供了內建的攔截器,可以攔截對未定義的方法和屬性的調用。這篇文章主要介紹了PHP的攔截器,以執行個體形式分析了常見的各類攔截器的用法,非常具有實用價值,需要的朋友可以參考下,具體如下:

PHP提供了幾個攔截器,用於在訪問未定義的方法和屬性時被調用,如下所示:

1、__get($property)
功能:訪問未定義的屬性是被調用

2、__set($property, $value)
功能:給未定義的屬性設定值時被調用

3、__isset($property)
功能:對未定義的屬性調用isset()時被調用

4、__unset($property)
功能:對未定義的屬性調用unset()時被調用

5、__call($method, $arg_array)
功能:調用未定義的方法時被調用

下面將通過一個小程式來說明這些攔截器的用途:

class intercept_demo{    private $xingming = "";    private $age = 10;       // 若訪問一個未定義的屬性,則將調用get{$property}對應的方法    function __get($property){        $method = "get{$property}";        if (method_exists($this, $method)){            return $this->$method();        }    }    // 若給一個未定義的屬性設定值,則將調用set{$property}對應的方法    function __set($property, $value){        $method = "set{$property}";        if (method_exists($this, $method)){            return $this->$method($value);        }       }       // 若使用者對未定義的屬性調用isset方法,    function __isset($property){        $method = "isset{$property}";        if (method_exists($this, $method)){            return $this->$method();        }    }       // 若使用者對未定義的屬性調用unset方法,    // 則認為調用對應的unset{$property}方法    function __unset($property){        $method = "unset{$property}";        if (method_exists($this, $method)){            return $this->$method();        }    }       function __call($method, $arg_array){        if (substr($method,0,3)=="get"){            $property = substr($method,3);            $property = strtolower(substr($property,0,1)).substr($property,1);            return $this->$property;        }    }       function testIsset(){        return isset($this->Name);    }       function getName(){        return $this->xingming;    }       function setName($value){        $this->xingming = $value;    }       function issetName(){        return !is_null($this->xingming);    }       function unsetName(){        $this->xingming = NULL;    }}$intercept = new intercept_demo();echo "設定屬性Name為Li";$intercept->Name = "Li";echo "\$intercept->Name={$intercept->Name}";echo "isset(Name)={$intercept->testIsset()}";echo "";echo "清空屬性Name值";unset($intercept->Name);echo "\$intercept->Name={$intercept->Name}";echo "";echo "調用未定義的getAge函數";echo "age={$intercept->getAge()}";

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.