我正在围绕一个现有类开发一个包装函数。
<?php
class wrapper extends client {
public function __call($name,$args) {
var_dump($name);
var_dump($args);
}
}
$client = new wrapper();
$client->users()->foobar();
?>
我的回答是:
string(5) "users"
array(0) {
}
我的目标是记录调用了哪个函数以及参数。
我怎么能看到users类上的函数foobar()被调用了。而不是仅仅";用户";?有合适的方法吗?
您要做的是实现Decorator模式,而不仅仅是扩展类。这很容易,因为我们有你已经使用过的神奇方法。但是您在包装类中遗漏了两个重要部分:
- 实例化包装的子类
- 对子类的中继函数调用
您的扩展将不起作用,因为只有当类没有具有给定名称的方法时,才会调用magic__call方法。因此,您需要没有这些方法的Wrapper-Decorator类。
样品:
class BetterWrapper {
protected $child;
public function __construct(){
$this->child = new Client();
}
public function __call($name,$args) {
var_dump($name);
var_dump($args);
return call_user_func_array(array($this->child, $name), $args);
}
}
试试这个吧。
有关__call方法的机制,请参阅此文档:http://php.net/manual/en/language.oop5.overloading.php#object.call