关于PHP的拦截器运用

WBOY
Release: 2016-06-13 10:56:04
Original
1121 people have browsed it

关于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对象增加了一个方法?

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!