为什么 PHP 在 Heredoc 语法中使用变量时不抛出任何 warning/error/notice?

Why PHP is not throwing any warning/error/notice upon using variables in Heredoc syntax?

我正在使用 PHP 7.2.2

以下是 PHP 手册中的声明:

Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

根据我的解释,这个语句的意思是现在(在PHP 7.2.2)Heredocs可以用于初始化class属性但是变量(不是 class 属性)不能在 Heredoc 中使用。

如果我对上述陈述的含义有错误的解释,请纠正我的错误并告诉我正确的含义。

如果我的解释是正确的,那么下面的代码示例是如何工作的?

<?php
class foo
{
    var $foo;
    var $bar;

    function __construct()
    {
        $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}

$foo = new foo();
$name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

输出:

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

我的问题是如何在 heredoc 中访问变量 $name,因为手册说在 heredoc 中使用变量是无效的?

为什么 PHP 没有生成任何 error/notice/warning?

你的例子没有显示Heredoc用于初始化class属性。

Heredoc 手册中,使用 Heredoc 初始化 class 属性 自 5.3 起有效:

class foo {
    public $bar = <<<EOT
bar
EOT;
}

用变量初始化 class 属性 不会:

class foo {
    public $bar = <<<EOT
{$_SERVER['PHP_SELF']}
bar
EOT;
}

Fatal error: Constant expression contains invalid operations

使用任何不计算为常量表达式的方法都是一样的:

class foo {
    public $bar = $_SERVER['PHP_SELF'];
}

Fatal error: Constant expression contains invalid operations

Properties手册一致:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.