PHP头条
热点:

关于PHP的拦截器运用


关于PHP的拦截器使用
成考终于结束了,又可以安心下来看看代码的书

好吧,继续学习PHP

php提供了内置的拦截器,可以拦截发送到一些未定义的方法和属性消息

先看下__get($property),它主要访问未定义的属性时被调用

看下示例:
class Coder{
  function __get($property){
    $method = "get{$property}";
    if(method_exists($this,$method)){
      return $this->$method();
    }
  }

  function getName(){
    return "SUN";
  }
}

$coder = new Coder();
print $coder->name;

程序执行后会输出SUN,如果程序里没有这个方法,就会什么也不做,会被解析成NULL

类似的方法还有__set(),__isset,__unset

下面主要来看下__call()这个方法,它是调用未定义的方法时被调用,有两个参数
1.$method, 这个是方法的名称;
2.$arg_array,是传递给要调用方法的所有参数(数组)

__call()方法对于实现委托的示例

class CoderWrite{
  function printName(Coder $c){
    print $c->getName();
  }
}

class Coder{
  private $write;
  function __construct(CoderWrite $cw){
    $this->write=$cw;
  }

  function __call($methodname,$args){
   if(method_exists($this->write,$methodname)){
     return $this->write->$methodname($this);
   }
  }

  function getName(){
    return "SUN";
  }
}

调用:$coder = new Coder(new CoderWrite());
$coder->printName();
_call()方法会被调用,然后查找CoderWrite对象中有没有printName()方法,有的话就会调用。呵呵,是不是变相的给Coder对象增加了一个方法?

www.phpzy.comtrue/phprm/23407.htmlTechArticle关于PHP的拦截器运用 关于PHP的拦截器使用 成考终于结束了,又可以安心下来看看代码的书 好吧,继续学习PHP php提供了内置的拦截器,可以拦截发送到一些未定义的方法和属性消息 先...

相关文章

PHP之友评论

今天推荐