Sunday 29 October 2017

php - error when using variable class name and static method

itemprop="text">

Running PHP 5.4, so I wasn't expecting
this, but I'm encountering the following
error:



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


Assume
you have a variable of stdClass setup as
follows:




$this->variable
= new stdClass();

$this->variable->other = array('class'
=>
'helloworld');


Now,
assume you want to access a static method of class
helloworld:



//
Standard call
$x =
helloworld::my_static_method();


// Call with variable
class name
$x =
$this->variable->other['class']::my_static_method();


When
calling the above using the variable class name, I receive the parsing error. What's
odd, is that if I do the following, no error is
presented:



$class =
$this->variable->other['class'];

$x =
$class::my_static_method();



To
me this seems very odd, can anyone think of a reason why the class name isn't resolving
correctly when using the first example versus the second?



Answer





can anyone
think of a reason why the class name isn't resolving correctly when using the first
example versus the
second?




The PHP
parser does not support such a syntax, and that's merely all. This is because the parser
has grown historically. I can't give more reason than
that.



It will be that with PHP 7 you can see
some changes on these syntax details working more into your expected direction href="https://wiki.php.net/rfc/uniform_variable_syntax" rel="nofollow
noreferrer">Uniform Variable
Syntax:




($variable->other['class'])::my_static_method();


But
until then, you can go around that with the help of
call_user_func:



call_user_func([$variable->other['class'],
'my_static_method']);
call_user_func($variable->other['class'] .
'::my_static_method');



Or
as you wrote your own, by creating a
variable:



$class =
$variable->other['class'];
$class::my_static_method();


Or
even a variable that looks like something
different:



${(int)!${0}=$variable->other['class']}::my_static_method();



Related
Material:




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...