I'm trying to get a static class variable to expand/resolve inside of a HEREDOC expression within a class constructor, but I cannot find a way to make it work. Please see my very simplified example below:
class foo {
private static $staticVar = '{staticValue}';
public $heredocVar;
public function __construct() {
$this->heredocVar = <<<DELIM
The value of the static variable should be expanded here: {self::$staticVar}
DELIM;
}
}
// Now I try to see if it works...
$fooInstance = new foo;
echo $fooInstance->heredocVar;
Which results in the following output:
The value of the static variable should be expanded here: {self::}
Additionally, I've tried various methods to reference the static variable without luck. I'm running PHP version 5.3.6.
As pointed out by Thomas, it is possible to use an instance variable to store a reference to the static variable, and subsequently use that variable inside the HEREDOC. The following code is ugly, but it does work:
class foo {
private static $staticVar = '{staticValue}';
// used to store a reference to $staticVar
private $refStaticVar;
public $heredocVar;
public function __construct() {
//get the reference into our helper instance variable
$this->refStaticVar = self::$staticVar;
//replace {self::$staticVar} with our new instance variable
$this->heredocVar = <<<DELIM
The value of the static variable should be expanded here: $this->refStaticVar
DELIM;
}
}
// Now we'll see the value '{staticValue}'
$fooInstance = new foo;
echo $fooInstance->heredocVar;
What about this answer?
I would set $myVar = self::$staticVar;
and then use $myVar
in the HEREDOC code.