drq61040 2012-10-07 21:53
浏览 38
已采纳

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

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.


Edit

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;
  • 写回答

1条回答 默认 最新

  • duanmo7075 2012-10-07 22:02
    关注

    What about this answer?

    I would set $myVar = self::$staticVar; and then use $myVar in the HEREDOC code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重