Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it allowed to call non-static methods with call_user_func?

Tags:

oop

php

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?

like image 739
sandelius Avatar asked Apr 14 '10 19:04

sandelius


People also ask

Can we call non static method?

A static method can call only other static methods; it cannot call a non-static method. A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables.

Can we call a non static method from a non static method?

“Can a non-static method access a static variable or call a static method” is one of the frequently asked questions on static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.

Can you call a non static method without an instance?

In a non-static method, the method use runtime or dynamic binding. So that we cannot access a non-static method without creating an instance.

How do you call a non static method from another class?

Example. The only way to access the non-static method of an abstract class is to extend it, implement the abstract methods in it (if any) and then using the subclass object you need to invoke the required methods.


1 Answers

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) :

like image 189
Pascal MARTIN Avatar answered Oct 12 '22 22:10

Pascal MARTIN