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

4
  • just a parser "feature", much like echo "$foo[1][2]" outputs Array[2] instead of whatever's stored at the [2] index. Commented Jul 13, 2015 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. Commented Jul 13, 2015 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? Commented Jul 13, 2015 at 19:09
  • I have edited this question for clarity. Is there any way to unmark it as duplicate? Commented Apr 19, 2017 at 20:08

1 Answer 1

0

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.