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.

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

报告相同问题?

悬赏问题

  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号