有没有一种特殊的方法,当我调用任何类的方法时,它会被调用?
下面是一个解释我问题的例子:
class Foo{
public function bar(){
echo 'foo::bar';
}
public function before(){
echo 'before any methods';
}
public function after(){
echo 'after any methods';
}
}
$foo = new Foo;
$foo->bar();
输出应为:
/*
Output:
before any methods
foo::bar
after any methods
*/
答案 0 :(得分:2)
/**
* @method bar
*/
class Foo{
public function __call($name, $arguments)
{
$myfunc = '_'.$name;
$this->before();
if (method_exists($this,$myfunc)) {
$this->$myfunc();
}
$this->after();
}
public function _bar(){
echo 'foo::bar';
}
public function before(){
echo 'before any methods';
}
public function after(){
echo 'after any methods';
}
}
$foo = new Foo;
$foo->bar();
答案 1 :(得分:1)
简而言之,没有。调用这些方法的唯一方法是在每个单独的方法中调用它们。
class Foo{
public function bar(){
$this->before();
echo 'foo::bar';
$this->after();
}
public function before(){
echo 'before any methods';
}
public function after(){
echo 'after any methods';
}
}
这将按预期输出:
/*
before any methods
foo::bar
after any methods
*/