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.
How can I use public constants outside a class it was declared in? You access them like any other static field or method on a class: by prefixing it with the name of the class they are on: TestConstant. y .
There are two ways to access class constants. Inside the class: The self keyword and Scope Resolution Operator ( :: ) is used to access class constants from the methods in a class. Outside the class: The class name and constant name is used to access a class constant from outside a class.
You can access all the variables by using the subclass object, and you don't have to create an object of the parent class. This scenario only happens when the class is extended; otherwise, the only way to access it is by using the subclass.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With