Is it ok to call non static methods with call_user_func in PHP 5.3?

前端 未结 1 699
北荒
北荒 2021-01-11 17:35

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         


        
相关标签:
1条回答
  • 2021-01-11 18:03

    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');
    

    Which will give you the following warning :

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

    (This would work perfectly fine if the method was declared as static... but it's not, here)


    For more informations, you can take a look at the callback section of the manual, which states, amongst other things (quoting) :

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


    If you get a strict error with an old version of PHP (e.g. 5.2), it's probably a matter of configuration -- I'm thinking about the error_reporting directive.

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

    0 讨论(0)
提交回复
热议问题