Reputation: 13005
I'm using PHP 7.2.2
Below is a statement from PHP Manual :
Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.
According to my interpretation, the meaning of this statement is now(in PHP 7.2.2)Heredocs can be used for initializing class properties but the variables(not class properties) can not be used inside Heredoc.
If I'm interpreting the meaning of above statement wrongly please do correct my mistake and tell me the correct meaning.
If my interpretation is correct then how the following code example is working?
<?php
class foo
{
var $foo;
var $bar;
function __construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
Output :
My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A
My question is how the variable $name is accessible inside heredoc as the manual is saying that usage of variable in heredoc is invalid?
Why PHP is not generating any error/notice/warning?
Upvotes: 1
Views: 313
Reputation: 79024
Your example DOES NOT show Heredoc used for initializing class properties.
From the Heredoc manual, initializing a class property using Heredoc works since 5.3:
class foo {
public $bar = <<<EOT
bar
EOT;
}
Initializing a class property with variables does not:
class foo {
public $bar = <<<EOT
{$_SERVER['PHP_SELF']}
bar
EOT;
}
Fatal error: Constant expression contains invalid operations
Which is the same using any method that does not evaluate to a constant expression:
class foo {
public $bar = $_SERVER['PHP_SELF'];
}
Fatal error: Constant expression contains invalid operations
Which is consistent with the Properties manual:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
Upvotes: 3