5

I was wondering if there is any possibility in PHP to do following;

<?php

class boo {
 static public $myVariable;

 public function __construct ($variable) {
   self::$myVariable = $variable;
 }
}

class foo {
  public $firstVar;
  public $secondVar;
  public $anotherClass;

 public function __construct($configArray) {
   $this->firstVar = $configArray['firstVal'];
   $this->secondVar= $configArray['secondVar'];
   $this->anotherClass= new boo($configArray['thirdVal']);
 }
}

$classFoo = new foo (array('firstVal'=>'1st Value', 'secondVar'=>'2nd Value', 'thirdVal'=>'Hello World',));

echo $classFoo->anotherClass::$myVariable;
?>

Expected OUTPUT : Hello World

I am getting following error; Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

I Googled and it is related to colon (double dots) in $classFoo->anotherClass::$myVariable

I wouldn't like to go all the trouble to change my other classes. Is there anyway around this problem?

Thank you for your help in advance.

P.S. I just didn't want to lose few hours on this to find a way around. I already spent yesterday 2.5 hours to change almost whole Jquery because customer wanted a change and today in the morning I was asked to take the changes back because they didn't want to use it (they changed their mind). I am just trying to avoid big changes right now.

2 Answers 2

13

You need to do:

$anotherClass = $classFoo->anotherClass;
echo $anotherClass::$myVariable;

Expanding expressions to class names/objects for static calls/constants is not supported (but expanding variables, as shown above, is).

Sign up to request clarification or add additional context in comments.

5 Comments

I don't know, why I haven't tried this one (: Thanks a lot for your help. Need to wait a bit more to accept your answer.
I'm pretty sure that's still not valid, unless it's new to PHP? EDIT: Also, what about using ${...} to eval a get_class result?
@Brad Christie: It's valid in 5.3.
@Brad Christie: What do you mean "eval a get_class result"?
@netcoder: When i think static I think to reference the name of the class, not the instance of the class being implemented in a static format (as 5.3 appears to do). I was having trouble getting $anotherClass::$myVariable to work, so instinctively I though to use get_class (basically emulate "boo::$myVariable", where boo would be get_class($classFoo->anotherClass)) but now I see there's no need. Long story short, I was trying to work around a problem that i didn't know didn't exist. ;p
0

If you do not care about memory and execution speed, this is correct.
It seems that reference would be better:

$classRef = &$classFoo->anotherClass;
echo $classRef;

Works for me.

Comments

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.