edelwater
edelwater

Reputation: 2802

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?

Upvotes: 4

Views: 4081

Answers (2)

MrSmith
MrSmith

Reputation: 380

I was trying 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 cursing for over an hour and not finding a clue I remembered that my local machine had a newer version of XAMPP installed and thus a different PHP version. So it seems that in PHP version 5.5.11 this was not possible but in version 5.6.8 you can actually combine strings.

I just installed the new XAMPP version on the test server to see if this is really true.

Upvotes: 2

BoltClock
BoltClock

Reputation: 723688

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';
    }
}

Upvotes: 9

Related Questions