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!
The most common syntax for here documents, originating in Unix shells, is << followed by a delimiting identifier (often the word EOF or END), followed, starting on the next line, by the text to be quoted, and then closed by the same delimiting identifier on its own line.
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.
The heredoc syntax is a way to declare a string variable. The heredoc syntax takes at least three lines of your code and uses the special character <<< at the beginning.
Heredoc's are a great alternative to quoted strings because of increased readability and maintainability. You don't have to escape quotes and (good) IDEs or text editors will use the proper syntax highlighting.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With