Access to class properties that are arrays in HEREDOC

The example below has two different syntaxes. One works, but the other does not! In fact, I expect it to be the other way around. The second syntax looks pretty crappy for 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 possible to use these curly braces and specify an associative index inside a HEREDOC?

edit : an expression inside curly braces must be written as it appeared outside the line!

+6
source share
2 answers

Yes it really is.

In heredocs and double-quoted strings, you can use the syntax {$...} , where ... is any valid PHP expression following $ .

This is similar to the syntax #{...} in Ruby, for example.

There is an example in the docs: http://php.net/manual/en/language.types.string.php#example-71

See complex curly syntax

+7
source

Separate it to make it clearer, starting with the one that works:

 <p>{$this->foo['two']}</p> // outputs correct: "2" 

It just works.

Now let's look at another one, you think that it does not work:

 <p>$this->foo[one]</p> // outputs: "Array[one]" 

What actually happens here:

$this->foo is read as the name of the variable to be converted to a string. Then this is Array . Comparable to:

 echo $this->foo; # Array 

The rest that follows is simply parsed as a string, so you get

 <p>Array[one]</p> 

for

 <p>$this->foo[one]</p> // outputs: "Array[one]" 

This is the same as:

 <p>{$this->foo}[one]</p> // outputs: "Array[one]" 

The curly braces help PHP to parse correctly. You can more specifically express what part you would like to be a variable expression in a line with curly braces.

+3
source

Source: https://habr.com/ru/post/895626/


All Articles