Frage

I have simple example code where I want to use object operator together with scope resolution to get class constant (PHP 5.5).

<?php


class A {
    const MY_CONST = 'This is my const';
}

class B {

    private $property;

    public function __construct(A $a) {    
        $this->property = $a;

        echo $a::MY_CONST."<br />"; // works (1)

        echo A::MY_CONST."<br />"; // works (2)

        $obj = $this->property;

        echo $obj::MY_CONST."<br />"; // works (3)

        echo $this->property::MY_CONST; // doesn't work (4)               
    }

}

$b = new B(new A);

The code is tested in PHP 5.5.12, I don't care about compatibility with earlier PHP versions in this question.

Question is - is it possible to access object const if the object is set as property of other class as in (4) and you want to use $this together with const name. 1 and 2 obviously works, simple assignment in 3 also works but makes one extra line.

If it is not possible is there any reason to deny it or simple PHP developers decided so or simple forgot about making it working? For me it's quite strange that 4 doesn't work but 3 is working without any problem

War es hilfreich?

Lösung

The answer to your question is: Yes, it is possible. But in one of threee round-about ways:

$tmp = $this->property;
return $tmp::MY_CONST;

Or, IMO, a bit more intuitive:

$class = get_class($this->property);
return $class::MY_CONST;

An alternative way of doing this would be:

$r = new RefletionClass($this->property);
return $r->getConstant('MY_CONSTANT');

As to the reason why your code generates a parser error, I'm not 100% sure. I can tell you, however, that the PHP grammar is quite complicated, and a tad messy.
I wouldn't be surprized, though, to learn that $this->foo::BAR is an expression that trips up the parser, which explains the parse error.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top