Constant tray class access not working

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 no longer access the constant:

 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 that I can just do echo LOL::FOO , but what if the class name is unknown? From this perspective, I only have access to this object / property, and I really do not want this WWW class to be β€œaware” of other classes and their names. It should just work with this object.

+6
source share
3 answers

You can make it a lot easier by assigning the lol property to a local variable, for example:

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

This is still stupid, but does not allow the use of reflections.

+2
source

If the class name is not known, you can use ReflectionClass to get the constant. Please note that you must use PHP 5 or more.

Example:

 $c = new ReflectionClass($this->lol); echo $c->getConstant('FOO'); // 1 

Starting with PHP 5.3.0, you can access the constant through a variable containing the class name:

 $name = get_class($this->lol); echo $name::FOO; // 1 

For more information, see Scope Resolution Operator - PHP

+1
source
 $lol = &$this->lol; echo $lol::FOO; .. unset($lol); 
0
source

Source: https://habr.com/ru/post/920490/


All Articles