11

当我call_user_func在 PHP 5.2 中使用非静态方法时,我收到一个严格警告:

Strict Standards: Non-static method User::register() cannot be called statically

但是在 PHP 5.3.1 上我没有收到这个警告。这是 PHP 5.3.1 中的错误还是警告已删除?

4

1 回答 1

27

完全没问题 - 但请注意,您必须传递一个作为类实例的对象,以指示应在哪个对象上调用非静态方法:

class MyClass {
    public function hello() {
        echo "Hello, World!";
    }
}

$a = new MyClass();
call_user_func(array($a, 'hello'));


你不应该使用这样的东西:

call_user_func('MyClass::hello');

这会给你以下警告:

Strict standards: `call_user_func()` expects parameter 1 to be a valid callback,
non-static method `MyClass::hello()` should not be called statically 

(如果该方法被声明为静态的,这会很好地工作......但它不是,在这里)


有关更多信息,您可以查看手册的回调部分,其中指出,除其他外(引用)

实例化对象的方法作为数组传递,该数组包含索引 0 处的对象和索引 1 处的方法名称。


如果您在使用旧版本的 PHP(例如 5.2)时遇到严格错误,则可能是配置问题——我正在考虑该error_reporting指令。

请注意,E_ALL包括E_STRICT PHP 5.4.0 引用

于 2010-04-14T19:31:53.483 回答