我想要一个每次引用(调用)类时都会调用的函数。 魔术函数 autoload 做类似的事情,但仅在引用的类不存在时才起作用。 我想制作一个在任何情况下都可以使用的功能。
例如:
<?php
class Foo {
static function bar () {
...
}
}
function __someMagicFunction ($name) {
echo 'You called class ' . $name;
}
Foo::bar(); // Output: You called class Foo
我希望输出为“You called class Foo”。
我该怎么做? 谢谢:)
最佳答案
好吧,没有简单的方法可以做到这一点,但这是可能的。不过,不推荐您实现此目标的方式,因为它会导致代码缓慢。然而,这里有一个简单的方法来做到这一点:
class Foo
{
//protected, not public
protected static function bar ()
{
}
protected function nonStaticBar()
{
}
public function __call($method, array $args)
{
//echoes you called Foo::nonStaticBar
printf('You called %s::%s', get_class($this), $method);
//perform the actual call
return call_user_func_array([$this, $method], $args);
}
//same, but for static methods
public static function __callStatic($method, array $args)
{
$calledClass = get_called_class();//for late static binding
printf('You called %s::%s statically', $calledClass, $method);
return call_user_func_array($calledClass . '::' . $method, $args);
}
}
$foo = new Foo;
$foo->nonStaticBar();//output: You called Foo::nonStaticBar
Foo::bar();//output: You called Foo::bar statically
__callStatic
使用 get_called_class
而不是 get_class(self);
的原因是它使您能够将魔术方法声明为 final
,并且仍然让它们在子类中按预期工作:
class Foobar extends Foo
{}
Foobar::bar();//output: You called Foobar::bar statically
demo
关于魔法方法的更多细节:
- The docs , 当然
- 我以前的一些答案 explaining why
__call
& co are slow - 以及为什么应该预先声明属性(与
__call
速度慢的原因相同)here
关于php - 上课通知 - php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31136696/