如何从PHP heredoc表达式中扩展静态类变量?

时间:2012-10-07 21:53:08

标签: php static-members heredoc

我正在尝试获取一个静态类变量来扩展/解析类构造函数中的HEREDOC表达式,但我找不到让它工作的方法。请参阅下面的简化示例:

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;

这导致以下输出:

The value of the static variable should be expanded here: {self::}

另外,我尝试过各种方法来引用静态变量而没有运气。我正在运行PHP版本5.3.6。

<小时/> 的修改

正如Thomas所指出的,可以使用实例变量来存储对静态变量的引用,然后在HEREDOC中使用那个变量。以下代码很难看,但确实有效:

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;

1 个答案:

答案 0 :(得分:2)

this answer怎么办?

我会设置$myVar = self::$staticVar;,然后在HEREDOC代码中使用$myVar