当我在抽象方法上调用call_user_func()时会发生什么?

时间:2014-01-13 21:55:16

标签: php abstract-class static-methods

假设我有以下抽象类:

abstract class A{
    abstract public function foo(){}
}

这个子类扩展了上面的抽象类:

class B extends A{
    public function foo(){ echo 'bar'; }
}

在我的代码中的其他地方,我打电话:

call_user_func( array('B', 'foo') );

据我在call_user_func()文档中可以看出,foo()将被静态调用:

  

也可以使用此函数静态调用类方法   将数组($ classname,$ methodname)传递给此参数。另外   可以通过传递来调用对象实例的类方法   此参数的数组($ objectinstance,$ methodname)。

然而,我的印象是自PHP 5.3+以来abstract static methods were not allowed/should not be used。是否无法声明抽象静态方法,但仍可使用::运算符或call_user_func()静态调用?我很困惑......

1 个答案:

答案 0 :(得分:2)

在PHP 5.5.5中,我得到:

Strict Standards: call_user_func() expects parameter 1 to be a valid callback, non-static method B::foo() should not be called statically in x line x

您可以使用B类对象来调用它:

// this is static because you state a class B
call_user_func( array('B', 'foo') );

//this is non-static because you pass an instance of class B
call_user_func( array(new B, 'foo') );

两者都显示bar