This question already has an answer here:
Since PHP version 5.3 we can call static method in a variable class like this:
class A
{
public static function foo()
{
echo 'bar';
}
}
$myVariableA = A::class;
$myVariableA::foo(); //bar
Today I've faced something tricky trying to do this in a class property, like that:
class A
{
public static function foo()
{
echo 'bar';
}
}
class B
{
protected $myVariableA;
public function __construct()
{
$this->myVariableA = A::class;
}
public function doSomething()
{
return $this->myVariableA::foo(); //parse error
}
}
$b = new B;
$b->doSomething();
This returns a parse error:
PHP Parse error: syntax error, unexpected '::'
If we change the doSomething() method to associate the class variable to a local variable, it works fine:
...
public function doSomething()
{
$myVariableA = $this->myVariableA;
return $myVariableA::foo(); //bar (no parse error)
}
...
The question is: why do the second format (with local variable) does work, but the first (with method property) does not?
Note that I'm not trying to solve the issue here (as my code is already working), but I want to understand exactly why I can use '::' in a normal variable, but not in a class property.
I'm using PHP 5.6.10.
echo "$foo[1][2]"
outputsArray[2]
instead of whatever's stored at the[2]
index. – Marc B Jul 13 '15 at 17:18