Tuesday, 2 August 2016

oop - PHP: variable class in a class property - why calling static method return parse error?

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



So, given the examples below, I'd like to understand why Class B works and Class C does not:



class A 
{
public static function foo()
{
echo 'bar';
}
}


class B
{
protected $myVariableA;

public function __construct()
{
$this->myVariableA = A::class;
}


public function doSomething()
{
$myVariableA = $this->myVariableA;
return $myVariableA::foo(); //bar (no error)
}
}

class C
{
protected $myVariableA;


public function __construct()
{
$this->myVariableA = A::class;
}

public function doSomething()
{
return $this->myVariableA::foo(); //parse error
}

}

$b = new B;
$b->doSomething();

$c = new C;
$c->doSomething();


Note that I'm not trying to solve the issue here, but I want to understand exactly why it happens (with implementation details, if possible).

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...