13

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

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?

1
  • You'll get the same warning on PHP5.3. Looks like your php5.3 and php5.2 configuration are different. Have a look at error_reporting. Commented Apr 14, 2010 at 19:35

1 Answer 1

31

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**][1] 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`**][2] directive.

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

Sign up to request clarification or add additional context in comments.

5 Comments

E_STRICT is supposed to be included in E_ALL in PHP 5.3 I think. Btw thank you, I instantiated the object and then it works just fine.
OK about instanciating the object :-) ;;; I don't think E_STRICT is included in E_ALL, even in PHP 5.3 -- I suppose it would be said so in the manual ;-)
E_ALL does include E_STRICT in 5.5 for sure.
Note that if the method is in the same class you can use call_user_func(array($this, 'hello')); such as explained here
one-liner call_user_func( [ ( new MyClass() ), 'hello' ] );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.