开发者

How to perform text concatenation in object variables in PHP?

If I use a "dot" to assign a value in开发者_如何学Python a variable in a PHP class, it fails.

For example:

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

How should I approach this otherwise?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜