Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing class constant trough property doesn't work

Example:

class LOL{
  const
    FOO = 1;
}

$x = new LOL;
$arr = array('x' => $x);

echo $x::FOO; // works
echo $arr['x']::FOO; // works too

But if I make my class instance a property, I can't access the constant anymore:

class WWW{
  protected $lol;

  public function __construct($lol){
    $this->lol= $lol;    
  }

  public function doSMth(){
    echo $this->lol::FOO; // fail. parse error.. wtf
  }
}

$w = new WWW;
$w->doSMth();

:(

I know I can just do echo LOL::FOO, but what if the class name is unknown? From that position I only have access to that object/property, and I really don't want that WWW class to be "aware" of other classes and their names. It should just work with the given object

like image 227
Alex Avatar asked Jul 14 '12 16:07

Alex


1 Answers

You can do this much easier by assigning the lol property to a local variable, like so:

public function doSMth(){
    $lol = $this->lol;
    echo $lol::FOO;
}

This is still silly, but prevents having to use reflections.

like image 153
Martijn Hols Avatar answered Oct 20 '22 08:10

Martijn Hols