PHP forward_static_call与call_user_func [英] PHP forward_static_call vs call_user_func
问题描述
forward_static_call
和call_user_func
同样的问题也适用于forward_static_call_array
和call_user_func_array
And the same question applies to forward_static_call_array
and call_user_func_array
推荐答案
区别仅在于,如果上层类层次结构并显式命名一个类,则forward_static_call
不会重置被叫类"信息,而call_user_func
在这种情况下会重置信息(但如果使用parent
,static
或self
仍不会重置信息).
The difference is just that forward_static_call
does not reset the "called class" information if going up the class hierarchy and explicitly naming a class, whereas call_user_func
resets the information in those circumstances (but still does not reset it if using parent
, static
or self
).
示例:
<?php
class A {
static function bar() { echo get_called_class(), "\n"; }
}
class B extends A {
static function foo() {
parent::bar(); //forwards static info, 'B'
call_user_func('parent::bar'); //forwarding, 'B'
call_user_func('static::bar'); //forwarding, 'B'
call_user_func('A::bar'); //non-forwarding, 'A'
forward_static_call('parent::bar'); //forwarding, 'B'
forward_static_call('A::bar'); //forwarding, 'B'
}
}
B::foo();
请注意,如果
Note that forward_static_call
refuses to forward if going down the class hierarchy:
<?php
class A {
static function foo() {
forward_static_call('B::bar'); //non-forwarding, 'B'
}
}
class B extends A {
static function bar() { echo get_called_class(), "\n"; }
}
A::foo();
最后,请注意,只能在类方法中调用forward_static_call
.
Finally, note that forward_static_call
can only be called from within a class method.
这篇关于PHP forward_static_call与call_user_func的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!