HEREDOC require {} to print multidimensional arrays values but on a normal array it doesn't. Why?

StackOverflow https://stackoverflow.com/questions/21291801

質問

When writing in HEREDOC and posting multidimentional array values it requires {}. On normal array no. Here an example:

$array = array('normal_key', 'normal_value');
$multidim = array(array('multi0_key', 'multi0_value'),
                  array('multi1_key', 'multi1_value')
               );          
$text1 =<<<EOBODY
    Hello World!<br />
    $array[0] $array[1]<br />
    $multidim[0][0] $multidim[0][1]<br />
    $multidim[1][0] $multidim[1][1]
EOBODY;

echo $text1;
//This prints:
/* Hello World!
*  normal_key normal_value
*  Array[0] Array[1]
*  Array[0] Array[1] */

$text2 =<<<EOBODY
    Hello World!<br />
    $array[0] $array[1]<br />
    {$multidim[0][0]} {$multidim[0][1]}<br />
    {$multidim[1][0]} {$multidim[1][1]}
EOBODY;

echo $text2;
//This prints:
/*  Hello World!
*   normal_key normal_value
*   multi0_key multi0_value
*   multi1_key multi1_value */

Why?

役に立ちましたか?

解決

That's normal. It's a PHP parser "bug" - it's not greedy when looking for arrays in strings:

$arr[1][2] = 'foo';
echo "$arr[1][2]";   non-greedy
echo $arr[1][2];  greedy, outputs 'foo'

is parsed as

echo $arr[1], "[2]";
     ^^^^^^^--array
              ^^^^--string

output: Array[2]

Echoing an array in string context will always output the literal word Array, and not the array's contents.

Using the {} notation forces PHP to suck in the entire array reference:

echo "{$arr[1][2]}"; // outpus "foo";

The "bug" applies to both normal ""-quoted strings, and HEREDOCs.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top