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()}";