0

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

Rafael Beckel
  • 2,199
  • 5
  • 25
  • 36
  • just a parser "feature", much like `echo "$foo[1][2]"` outputs `Array[2]` instead of whatever's stored at the `[2]` index. – Marc B Jul 13 '15 at 17:18
  • @john-conde I don't think its duplicate. In the referred question, the guy is trying to access a method of a instanced object with '::' when he should use '->'. I'm trying to call a static method of a class that was not instanced. The code works with a local variable, but does not with a class property and I want to understand why. – Rafael Beckel Jul 13 '15 at 18:54
  • @MarcB I would like to understand why the second case works (with local variable) and the first one (with the class property) does not. If we can use '::' in a local variable to call a static method, why we cannot use it in a class property? – Rafael Beckel Jul 13 '15 at 19:09
  • I have edited this question for clarity. Is there any way to unmark it as duplicate? – Rafael Beckel Apr 19 '17 at 20:08

1 Answers1

0

Based on this, the error message is something to with the double semicolon ( ::).

On your doSomething(), try using myVariableA->foo();

Community
  • 1
  • 1
Jon
  • 29
  • 6
  • The question is not about what T_PAAMAYIM_NEKUDOTAYIM is. I know it means :: and it's also mapped as T_DOUBLE_COLON (I'll edit the question to clarify, thanks). – Rafael Beckel Jul 13 '15 at 18:38