使用 heredoc 语法时数组到字符串的转换

Array to string conversion when using heredoc syntax

我 运行 遇到了一个奇怪的问题,我似乎无法使用 heredoc 语法回显数组值:

<?php

$arr = array(
    array("string 1"),
    array("string 2"),
    array("string 3")
    );

// string 3
echo $arr[2][0];

// Notice: Array to string conversion
// Var dump: string(8) "Array[0]"
echo <<<EOT
$arr[2][0]
EOT;

我觉得这是我现在应该知道的事情,但我找不到发生这种情况的任何原因或如何解决它。有谁愿意赐教吗?

在 heredoc 中使用 {}

echo <<<EOT
{$arr[2][0]}
EOT;

输出:

string 3string 3

当涉及到字符串中的数组或对象引用时,需要 complex parsing 使用 {}。来自 link 的信息:(示例也可以在那里找到)

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {$ to get a literal {$.

来自 Strings 上的 PHP 手册中的示例:

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

由于 heredoc 语法等同于带引号的字符串,因此您需要在值周围使用大括号:

echo <<<EOT
{$arr[2][0]}
EOT;

输出:

string 3

Demo on 3v4l.org