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.

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

报告相同问题?