【问题标题】:How can I expand a static class variable from within a PHP heredoc expression?如何从 PHP heredoc 表达式中扩展静态类变量?
【发布时间】:2012-10-07 21:53:07
【问题描述】:

我试图让一个静态类变量在类构造函数中的 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 中使用 that 变量。以下代码很难看,但确实有效:

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;

【问题讨论】:

    标签: php static-members heredoc


    【解决方案1】:

    this answer 呢?

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

    【讨论】:

    • 没有人声称它很漂亮。 ;-)
    • 我想说这并不比使用 private static 类属性更粗鲁:)
    猜你喜欢
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2015-03-11
    • 2023-01-13
    • 1970-01-01
    相关资源
    最近更新 更多