php - 如何从 PHP 定界符表达式中扩展静态类变量?

标签 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 中使用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;

最佳答案

怎么样this answer

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

关于php - 如何从 PHP 定界符表达式中扩展静态类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12773181/

相关文章:

c++ - 从相同类型的静态成员进行类内初始化

javascript - 将 PHP Heredoc 与 Javascript 模板文字相结合

php - 访问 HEREDOC 中作为数组的类属性

Javascript 文档

php - 获取目录名称并在 PHP 中拆分它们

php - 如何在逗号分隔的行值中使用 codeigniter

c# - 如何在 parent 静态方法中使用 child 的变量?

php - 为什么我无法在 _id 在 mongodb 中找到记录

javascript - 如何从可点击的行表创建新页面

c++ - 由于 header 中的特化初始化而避免重复符号?