PHP 5.5: access to the static member of a dynamic class class stored in an object

Assume the following:

class a {
  public static $foo = 'bar';
}
class b {
  public $classname = 'a';
}
$b = new b();

Somehow (braces, etc.), you can directly access $ foo without creating an "unexpected :: (T_PAAMAYIM_NEKUDOTAYIM)":

$b->classname::$foo //should result in "bar" not in an "unexpected :: (T_PAAMAYIM_NEKUDOTAYIM)"

I know and am using the following workaround:

$c = $b->classname;
$c::$foo;

but I would like to know if he has another good way to directly access $ foo.

+4
source share
3 answers

You can do this as using variable variables like

class a {
  public static $foo = 'bar';

  public function getStatic(){
      return self::$foo;
  }
}
class b {
  public $classname = 'a';
}
$b = new b();
$a = new a();
echo ${$b->classname}->getStatic();//bar
+1
source

For writing in PHP 7, the following works:

echo  $b->classname::$foo;

, , ( " " ), -.

+1

You need to build this expression:

$ string = a :: $ foo;

and you can use eval like this:

eval('$string=' . $b->classname . '::$foo;');

print($string);
0
source

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


All Articles