4

We assume the following:

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

Is it somehow (curly braces etc.) possible to access $foo directly without generating an "unexpected :: (T_PAAMAYIM_NEKUDOTAYIM)":

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

I know and use the following workaround:

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

but I would like to know if it exists another nice way to do access $foo directly.

Thomas Lauria
  • 858
  • 1
  • 7
  • 15
  • possible duplicate of [accessing static methods using a variable class name (PHP)](http://stackoverflow.com/questions/5059957/accessing-static-methods-using-a-variable-class-name-php) – raina77ow Sep 30 '15 at 07:09
  • No its no duplicate as mentioned above, since the workaround is using what is answered in the above question. – Thomas Lauria Sep 30 '15 at 08:12

3 Answers3

1

You can do it like using variables variable like as

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
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
  • I think the point is to get 'bar' without knowing the content of property classname in b. If you need to create a new a(), what's the point? – Amarnasan Sep 30 '15 at 07:28
  • I don't have an instance of "a" (and I can't create one because of missing constructor parameters), so your solution would not work. – Thomas Lauria Sep 30 '15 at 08:08
1

For the record, the following works in PHP 7:

echo  $b->classname::$foo;

Older versions need a workaround like the one you are using (which is already the "nicest" one), because the parser worked differently.

Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111
0

You need to build this expression:

$string = a::$foo;

and you can use eval this way:

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

print($string);
Amarnasan
  • 14,939
  • 5
  • 33
  • 37