gpt4 book ai didi

php - 使用 heredoc 语法访问字符串中的静态变量的正确方法?

转载 作者:行者123 更新时间:2023-12-04 02:19:59 26 4
gpt4 key购买 nike

假设我在我的类中有一个名为 $_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;

输出:

Notice: Undefined variable: _staticVar in /path/to/file.php on line some_line_number

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

PHPdocs对于 heredoc对此什么也没说。


我试过这个:

    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;

它不起作用。
输出:

Notice: Undefined variable: _staticVar in /path/to/file.php on line some_line_number

<br/>This is the content of my static variable,
   
which is not getting accessed properly in heredoc syntax.<br/>


这是我的 PHP 设置:

display_startup_errors = on
display_errors = On
error_reporting = E_ALL | E_STRICT

最佳答案

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

    $_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;

插入 undefined variable $something$_staticVar,这会导致空字符串和通知。

    echo <<<eos

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

eos;

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

关于php - 使用 heredoc 语法访问字符串中的静态变量的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8773236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com