Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform text concatenation in object variables in PHP?

If I use a "dot" to assign a value in a variable in a PHP class, it fails.

For example:

class bla {
       public $a = 'a' . 'b';
}

How should I approach this otherwise?

like image 210
edelwater Avatar asked Dec 21 '22 17:12

edelwater


1 Answers

You can only do that in the constructor, as class variables/properties must be initialized on declaration with constant expressions. From the 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.

This means you can't use any operators or function calls.

class bla {
    public $a;

    public function __construct() {
        $this->a = 'a' . 'b';
    }
}
like image 198
BoltClock Avatar answered Mar 08 '23 09:03

BoltClock