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?
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.
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();
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With