Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing class properties that are arrays in HEREDOC

Tags:

php

heredoc

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!

like image 371
Nick Avatar asked Aug 22 '11 20:08

Nick


People also ask

What 3 characters must you type to begin a heredoc?

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.

What is heredoc and Nowdoc in PHP?

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.

What is heredoc syntax?

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.

Should I use heredoc?

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.


1 Answers

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

like image 115
Arnaud Le Blanc Avatar answered Sep 22 '22 12:09

Arnaud Le Blanc