/** * person class */ class Person { /** * person class -> function say */ public static function say($i) { echo "hi-->"; var_dump($i); //return "hi"; } } class Dog{ public function say() { echo "wang !"; } }
APO的主要思路 (__call魔术方法:调用一个没有的方法时执行)
interface Monitor{ public function __construct($class); public function __call($name, $arguments); } abstract class Event{ public abstract function before(); public abstract function after(); } class MonitorBase implements Monitor{ private $classes = null; public function __construct($class){ $this->classes=$class; } public function __call($name, $arguments){ echo "前置输出"; echo $name; call_user_func(array($this->classes,$name),$arguments); echo "后置输出"; } }
测试 :
$p = new MonitorBase(new Person()); $p->say("888",'666',array(1,2,3,65,4)); $d = new MonitorBase(new Dog()); $d->say();
结果:
最后:细心的读者可能注意到 抽象类Event 没有用到
这个其实可以让 Person 和Dog 继承然后重写 before()和after(),这样每一个类都有自己的前置和后置通知了...