【问题标题】:What happens when I call_user_func() on an abstract method?当我在抽象方法上调用_user_func() 时会发生什么?
【发布时间】:2014-01-13 21:55:15
【问题描述】:

假设我有以下抽象类:

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() 将被静态调用:

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

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

【问题讨论】:

  • 是的。它调用该方法没有错误。我只是在概念上感到困惑,一方面,不应声明抽象静态方法,但另一方面,PHP 允许您调用它们。
  • 在 PHP 中,any 方法可以被静态调用(在许多语言中,没有关键字要求函数被非静态调用);该方法具有abstract 父级这一事实根本没有区别。另外,请注意“不应该”和“不能”之间的区别——“严格标准”是最温和的警告形式之一,[没有版本实际上不允许 abstract static function[(3v4l.org/E1E5Y)。

标签: php abstract-class static-methods


【解决方案1】:

在 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

【讨论】:

    猜你喜欢
    • 2011-08-08
    • 2018-07-23
    • 2015-06-19
    • 2016-11-11
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多