Search code examples
phpclassheredocvariable-initializationclass-properties

Why PHP is not forbidding me from initializing class properties using heredoc syntax?


I'm using PHP 7.1.11

As mentioned in the PHP manual :

Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

The above sentence is saying that class properties can not be initialized using heredoc syntax since PHP 5.3.

I'm using PHP 7.1.11 and initializing class property using heredoc syntax but I didn't get any error and the class property got initialized.

Why so?

Consider my below working code for it :

<!DOCTYPE HTML>
<html>
  <head>
    <title>Example</title>
  </head>
  <body>
  <?php
    class foo {
      public $bar = <<<EOT
                    barti
EOT;
    }

    $j = new foo();
    echo $j->bar;
  ?>
  </body>
</html>

The output of above code is

barti

Solution

  • As your source already points out since PHP 5.3, this limitation is valid only for heredocs containing variables. Your example code does not contain any variables, so it works as designed.


    However, what does not work is using variables in the heredoc like shown below:

        class foo {
          public $bar = <<<EOT
                        barti $someVariable // nor does {$someVariable}
    EOT;
        }
    
        $j = new foo();
        echo $j->bar;
    

    This throws an error:

    Fatal error:  Constant expression contains invalid operations in [...]
    

    NOTE

    This 'issue' does not come from heredocs. You cant initialize any class property to the result of a function or variable. Just try it without heredoc:

    class foo {
    
      public $bar = $test;
    }
    
    $j = new foo();
    echo $j->bar;
    

    Executing this code throws the exact same error.