Tuesday 30 August 2016

PHP variable class static method call



I have a property that stores a class name as a string. I then want to use this to call a static method of said class. As far as I know, this is possible since PHP 5.3. I am running 5.6.x on a vagrant box.



I want to do this:



$item = $this->className::getItem($id);



But I get the following error:



Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)...


The following works fine:



$c = $this->className;
$item = $c::getItem($id);



Any idea why? Is this not the same thing?


Answer



The problem is that you are access are property from a class in the first useage, but then in the second try you are parsing the value of the class property (into $c), what is a classname as string, and this can used for static calls to static class functions. The first try, trys to access the static method on an string (the class property).



class a {
static function b(){echo'works';}
}
$a='a';
$a::b();



But the real issue of the error is, that this ->FooBar:: is an syntax error in PHP.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...