设计问题/ PHP:我有一个方法类.当调用类中的任何方法时,我想随时调用外部函数.我想把它变成通用的所以当我添加另一个方法时,流程也适用于这个方法.
简化示例:
<?php
function foo()
{
return true;
}
class ABC {
public function a()
{
echo 'a';
}
public function b()
{
echo 'b';
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我需要在调用a()或b()之前调用foo().
我怎样才能做到这一点?
保护你的方法,使它们不能从类外部直接访问,然后使用magic __call()方法来控制对它们的访问,并在调用你的foo()后执行它们
function foo()
{
echo 'In pre-execute hook', PHP_EOL;
return true;
}
class ABC {
private function a()
{
echo 'a', PHP_EOL;
}
private function b($myarg)
{
echo $myarg, ' b', PHP_EOL;
}
public function __call($method, $args) {
if(!method_exists($this, $method)) {
throw new Exception("Method doesn't exist");
}
call_user_func('foo');
call_user_func_array([$this, $method], $args);
}
}
$test = new ABC();
$test->a();
$test->b('Hello');
$test->c();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4783 次 |
| 最近记录: |