是否允许使用 call_user_func 调用非静态方法? [英] Is it allowed to call non-static methods with call_user_func?

查看:173
本文介绍了是否允许使用 call_user_func 调用非静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I use call_user_func on a non-static method in PHP 5.2 I get a Strict Warning:

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

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

But on PHP 5.3.1 I don't get this warning. Is this a bug in PHP 5.3.1 or is the warning removed?

推荐答案

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

It is perfectly OK -- but note that you have to pass an object that's an instance of your class, to indicate on which object the non-static method shall be called :

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

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


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


You should not use something like this :

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 处.

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.


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

请注意,E_ALL 包括 E_STRICT 来自 PHP 5.4.0 (引用) :

Note that E_ALL includes E_STRICT from PHP 5.4.0 (quoting) :

这篇关于是否允许使用 call_user_func 调用非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆