0

I'm getting an error on line 5 of the code below when trying to concat two strings. I know I can simply combine the strings "a default value\n", but I would like to know why the following doesn't work as is.

<?php
    class SimpleClass
    {
        // property declaration
        public $var = 'a default value' . "\n"; //ERROR ON THIS LINE

        // method declaration
        public function displayVar() {
            echo $this->var;
        }
    }

    $a = new SimpleClass();
    echo $a->var;
    $a->displayVar();
?>
Govind Rai
  • 14,406
  • 9
  • 72
  • 83
  • 1
    "[class property declarations] 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." http://php.net/manual/en/language.oop5.properties.php -- Basically, you can't concatenate there. If you need to do anything more than provide a static value you're going to have to do it in the constructor. – Sammitch Dec 29 '16 at 20:29
  • https://3v4l.org/4BoCa It works fine? – Farkie Dec 29 '16 at 20:30
  • 4
    The code would work in PHP 5.6 or newer: https://wiki.php.net/rfc/const_scalar_exprs – Shira Dec 29 '16 at 20:30

0 Answers0