【问题标题】:Proper way to access a static variable inside a string with a heredoc syntax?使用heredoc语法访问字符串中的静态变量的正确方法?
【发布时间】:2012-02-05 02:11:51
【问题描述】:

假设我的班级中有一个名为 $_staticVar 的静态变量,我正试图像这样访问它。该变量有一个成员aString,其字符串值为"my static variable"

    echo <<<eos

    <br/>This is the content of my static variable, 
    self::$_staticVar->$aString
    which is not getting accessed properly in heredoc syntax. <br/>

eos;

输出:

注意:未定义变量:/path/to/file.php 中的 _staticVar 位于 some_line_number 行


这是我的静态变量的内容,
self::->我的静态变量,
在 heredoc 语法中无法正确访问。

heredocPHPdocs 对此没有任何说明。


我试过这个:

    echo <<<eos

    <br/>This is the content of my static variable,<br/>
    {${self::$_staticVar->$aString}}<br/>
    which is not getting accessed properly in heredoc syntax. <br/>

eos;

它不起作用。
输出:

注意:未定义变量:/path/to/file.php 中的 _staticVar 位于 some_line_number 行


这是我的静态变量的内容,
   
在 heredoc 语法中无法正确访问。


这是我的 PHP 设置:

display_startup_errors = 开启
display_errors = 开启
error_reporting = E_ALL | E_STRICT

【问题讨论】:

  • 我没有投反对票,而是尝试提供一个更实用的示例。即使对于最有经验的开发人员来说,阅读所有这些“something”和“somevar”真的很枯燥、令人困惑且难以回答!只是一个提示:)
  • @Kieran 我会用其他字符串来改变它。取点。 :)
  • 谢谢。我已通过 +1 恢复平衡

标签: php string heredoc


【解决方案1】:

我相当肯定您必须使用本地或导入的变量进行字符串插值。最简单的解决方案?为什么,当然是本地化:

    $_staticVar = self::$_staticVar; // or did you mean self::_staticVar? Not too clear on that.

    echo <<<eos

    <br/>Something {$_staticVar->something} more of something <br/>

eos;

至于您的示例不起作用的原因:

    echo <<<eos

    <br/>Something self::$_staticVar->{$something} more of something <br/>

eos;

对未定义的变量$something$_staticVar 进行插值,结果为空字符串和通知。

    echo <<<eos

    <br/>Something {${self::$$_staticVar->{$something}}} more of something <br/>

eos;

插入绝对不存在且永远不会存在的东西的值,这真的很令人困惑,但你知道它不起作用。

【讨论】:

  • 我知道我可以把它变成本地的。关键是是否有一种方法可以在不使其本地化的情况下进行。 :)
  • @ThinkingMonkey:不,你不能。放弃吧。
  • 因为,我没有看到任何地方提到它不能完成!
  • @ThinkingMonkey:我的回答中提到了 :) 说真的,插值文档提到它必须以 $ 开头才能计算在内。否则,you get an unexpected T_PAMAAYIM_NEUKODTAYIM.
  • 我认为没有任何解决方案,否则将字符串之外的静态变量值替换并在以$开头的局部变量中分配它
【解决方案2】:

您可以在这个示例类中展示如何从字符串内部访问/调用静态方法或属性。

您必须将类名存储在变量中,这样您就可以通过该变量访问类元素,是的,您可以访问静态变量和静态方法。

<?php

class test {
    private $static = 'test';
    // static Method
    static function author() {
        return "Frank Glück";
    }
    // static variable
    static $url = 'http://www.dozent.net';
    public function dothis() {
       $self = __CLASS__;
       echo <<<TEST
           {${$this->self}}::author()}} // don't works
           {${!${''}=static::author()}} // works
           {$self::author()} // works
TEST;
    }
}

$test = 'test'; // this is the trick, put the Classname into a variable

echo "{$test::author()} {$$test::$url}";
echo <<<HTML
<div>{$test::author()}</div>
<div>{$$test::$url}</div>
HTML;

【讨论】:

    猜你喜欢
    • 2015-07-22
    • 2012-06-29
    • 2014-04-01
    • 2012-03-11
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 2011-06-30
    相关资源
    最近更新 更多