【发布时间】:2012-03-16 12:56:55
【问题描述】:
我想知道每次在类中调用方法时是否有一种方法可以在 PHP 中执行 sn-p。类似于 __construct() 的工作方式,但应该在每个方法调用时调用它。
【问题讨论】:
-
为什么?如果需要的话,这听起来像是糟糕的设计。
标签: php methods call invoke code-snippets
我想知道每次在类中调用方法时是否有一种方法可以在 PHP 中执行 sn-p。类似于 __construct() 的工作方式,但应该在每个方法调用时调用它。
【问题讨论】:
标签: php methods call invoke code-snippets
您可能正在寻找__call()。每当调用不可访问的方法时,都会调用它。
class MyClass {
protected function doStuff() {
echo "doing stuff.";
}
public function __call($methodName, $params) {
echo "In before method.";
return $this->doStuff();
}
}
$class = new MyClass();
$class->doStuff(); // In before method.doing stuff.
【讨论】:
$myClass->callMethod('methodName', array('args')) 之类的方法,但这似乎是一个非常糟糕的解决方案
我可以建议您使用面向方面的库来满足您的需求。您将能够为方法(正则表达式)创建一个切入点,并且只需提出一个建议(闭包)以在每个方法之前/之后或周围调用。 你可以看看我的图书馆:Go! AOP PHP
【讨论】: