假设我的班级中有一个名为$ _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上
&lt; br /&gt;这是我的静态变量的内容,
self :: - &gt;我的静态变量,
在heredoc语法中无法正确访问。&lt; br /&gt;
我试过这个:
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;
它不起作用。
输出:
注意:未定义的变量:_staticVar in /path/to/file.php on some_line_number
&lt; br /&gt;这是我的静态变量的内容,
在heredoc语法中无法正确访问。&lt; br /&gt;
这是我的PHP设置:
display_startup_errors = on
display_errors = On
error_reporting = E_ALL | E_STRICT
答案 0 :(得分:3)
我很确定你必须使用本地或导入的变量进行字符串插值。最简单的解决方案?为什么,当然是当地的:
$_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;
插入绝对不存在且永远不会存在的东西的价值,这一切都让人感到困惑,但你知道它不起作用。
答案 1 :(得分:2)
您可以在此示例类中进行演示,以显示如何从字符串内部访问/调用静态方法或属性。
您必须将类名存储在变量中,以便可以访问此变量的classelements,是的,您可以访问静态变量和静态方法。
<?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;