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.

2

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
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.

Comments

0

You need to build this expression:

$string = a::$foo;

and you can use eval this way:

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

print($string);

5 Comments

OP asked for a "nice" way ;-)
Yeah, well, I don't think he'll get it nicer than he already did, just offering alternatives.
ACK. But recommending eval goes a bit too far, don't you think?
Guess that's up to OP to "eval" (wink, wink)
I am also agreeing that eval is no nice way ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.