How to concatenate text in object variables in PHP?

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

For instance:

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

How can I approach this otherwise?

+4
source share
2 answers

You can only do this in the constructor, since class / property variables must be initialized in a declaration with constant expressions. From manual :

This declaration may include initialization, but this initialization must be a constant value, that is, it must be able to be evaluated at compile time and should not depend on runtime information for evaluation.

This means that you cannot use any calls to operators or functions.

 class bla { public $a; public function __construct() { $this->a = 'a' . 'b'; } } 
+9
source

I tried the exact same thing:

 class someClass{ public $var = APP . DIRECTORY_SEPARATOR . "someFolder"; } 

This, however, worked on my local machine, but not on the server. After a curse of more than an hour and without finding a hint, I remembered that a newer version of XAMPP was installed on my local machine, and therefore a different version of PHP. It seemed like this was not possible in PHP version 5.5.11, but in version 5.6.8 you can combine strings.

I just installed the new version of XAMPP on the test server to make sure that this is true.

+2
source

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


All Articles