PHP提供了内置的拦截器(intercepter),它可以拦截发送到未定义的属性或者方法的消息。它也被称为重载。不过我们为了避免和java和c++中的重载歧义还是叫拦截器。
拦截器可以是类更加完善和安全。对于调用的未知的属性或者方法可以自定义的处理。不管是自己猜测处理或者返回自定义的信息。
- <?php
- /**
- * PHP5中拦截器学习测试
- * __get( $property ) 访问未定义的属性时候被调用
- * __set( $property, $value) 给未定义的属性赋值时被调用
- * __isset( $property ) 给未定义的属性调用isset()时候被调用
- * __unset( $property ) 给未定义的属性调用unset()的时候被调用
- * __call( $method, $arg_array ) 调用未定义的方法时候被调用
- *
- */
- error_reporting(E_ALL);
- class person {
- public $name;
- public $age;
- public function __get( $property ) {
- return null;
- }
- public function __set( $property, $value) {
- return null;
- }
- public function __isset( $property ) {
- return false;
- }
- public function __unset( $property ) {
- return true;
- }
- public function __call( $method,$arg_array ) {
- return $arg_array;
- }
- public function initialize($name,$age) {
- $this->name = $name;
- $this->age = $age;
- return true;
- }
- }
- $person = new person();
- $person->sex; //返回null 因为类中没有定义这个属性
- isset($person->age); //如果类中有这个属性 但是没有赋值 那么不会 不会走__isset 会直接返回false或者true
- $person->sex = 'male';//如果对一个不存在的属性定义那么会调用__get 方法
- $person->init('ZhangSan','20');// 这个会走__call 参数会当作数组 $arg_array传入
- unset($person->sex);//这里会调用__unset 方法
转载于:https://blog.51cto.com/phpzf/804700