There’s two different syntaxes in the example below. One works and the other does not! Actually I would expect it to be the other way round. The second syntax looks quite crappy to me.
<?php
class Vodoo
{
public $foo = array();
public function __construct()
{
$this->foo = array('one' => 1, 'two' => 2, 'three' => 3);
}
public function getFoo()
{
$return = <<<HEREDOC
<p>$this->foo[one]</p> // outputs: "Array[one]"
<p>{$this->foo['two']}</p> // outputs correct: "2"
HEREDOC;
return $return;
}
}
$bar = new Vodoo;
echo $bar->getFoo();
?>
Is it ok to use these curly braces and quote the associative index inside the HEREDOC?
edit: The expression inside the curly braces has to be written the way it’d appear outside the string!
Yes, this is valid.
In heredocs and double quoted strings you can use the syntax
{$...}where...is any valid PHP expression following a$.This is similar to the
#{...}syntax in Ruby, for example.There is an example of this in the docs: http://php.net/manual/en/language.types.string.php#example-71
See complex curly syntax