在PHP中,在类的任何方法之前调用特殊方法
有没有一个特殊的方法,当我调用任何类的方法时,它都会被调用 下面有一个例子可以解释我的问题:在PHP中,在类的任何方法之前调用特殊方法,php,oop,magic-methods,Php,Oop,Magic Methods,有没有一个特殊的方法,当我调用任何类的方法时,它都会被调用 下面有一个例子可以解释我的问题: class Foo{ public function bar(){ echo 'foo::bar'; } public function before(){ echo 'before any methods'; } public function after(){ echo 'after any methods'; } } $
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
*/
简而言之,不是。调用这些方法的唯一方法是在每个单独的方法中调用它们
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
*/
就我个人而言,我不喜欢这个解决方案,但您可以使用神奇的方法调用:
/**
* @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();
不,没有什么是这样的,但是有两个神奇的方法
\uuuu call()
和\uuuu callStatic()
,它们在调用不可访问的方法时被调用,或者换句话说,这些方法在类中不存在。不,你必须从类的其他方法中调用这个方法。这更像是一种黑客行为。不管方法是否存在,这都将执行前面和后面的函数。@BrandonWhite:我认为人们足够聪明,可以在方法_exists;-)中放置before()和after()只是提醒一下:\u call
仅在实际调用的方法不存在时调用。当我试图弄清楚\u call
是在实际方法之前还是之后被调用时,我找到了这个SO链接,但是如果该方法确实存在,它根本不会被调用。