假设我的类中有一个名为$_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;
输出:
注意:未定义的变量:_第some_line_number行/path/to/file.php中的staticVar
<br/>这是我的静态变量
的内容self::->我的静态变量,
在heredoc语法中无法正确访问<br/>
heredoc
的PHPdocs没有对此做任何说明。
我试过这个:
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;
而且它不起作用
输出:
注意:未定义的变量:_第some_line_number行/path/to/file.php中的staticVar
<br/>这是我的静态变量
nbsp
在heredoc语法中无法正确访问<br/>
这是我的PHP设置:
display_startup_errors=打开
display_errors=打开
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;
插入未定义的变量$something
和$_staticVar
,结果是一个空字符串和一个通知。
echo <<<eos
<br/>Something {${self::$$_staticVar->{$something}}} more of something <br/>
eos;
插入一些肯定不存在也永远不会存在的东西的价值,这一切都很令人困惑,但你知道它不起作用。
您可以在这个示例类中演示如何从字符串内部访问/调用静态方法或属性。
您必须将类名存储在变量中,这样您就可以通过该变量访问类元素,是的,您可以访问静态变量和静态方法。
<?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;