Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call_user_func(array(self, 'method')) - do I have to name the class?

Tags:

oop

php

In PHP, call_user_func(array(self, 'method_name')) doesn't work. The self keyword cannot be used in that context. I need to actually include the name of the class call_user_func(array('class_name', 'method_name')).

However, if I'm not in a static function, the $this variable does work in that context. Why the difference?

like image 695
TRiG Avatar asked Aug 24 '11 13:08

TRiG


5 Answers

Since PHP 5.5, you can do [self::class, 'methodName'].

::class is really useful for situations where you have a class name (maybe a local alias) and you need to generate the full class name as a string.

like image 76
Mark Jaquith Avatar answered Nov 20 '22 10:11

Mark Jaquith


self is just an undefined constant, so it expresses 'self'. So these two are the same:

array(self, 'method_name');
array('self', 'method_name');

And depending on the PHP version you use, this actually works, see Demo.

In case it does not work with your PHP version, some alternatives are:

call_user_func(array(__CLASS__, 'method_name'));

or

call_user_func(__CLASS__.'::method_name'));

or (in case you don't need call_user_func):

self::method_name();
like image 30
hakre Avatar answered Nov 20 '22 10:11

hakre


If you want the name of the current class context, use get_class() (without any parameters) or __CLASS__.

You've already written the difference; self is a keyword, and is not usable as a reference in an array (what kind of type should that be in PHP?). get_class() returns a string, and the array()-callback supports using a string as the first name to do a static call.

like image 12
MatsLindh Avatar answered Nov 20 '22 11:11

MatsLindh


You can try with __CLASS__ to get the class name. Also it may work to use call_user_func('self::method_name') directly, but I didn't test it and the documentation about callbacks doesn't say anything about this.

like image 3
Alin Purcaru Avatar answered Nov 20 '22 12:11

Alin Purcaru


In PHP 5.3, you can write call_user_func('self::method') or call_user_func(array('self', 'method')). I suppose the latter could work in older versions as well.

like image 2
Adrian Heine Avatar answered Nov 20 '22 10:11

Adrian Heine