string concatenation with constants

2019-09-22 03:44发布

I have only PHP 5.4 available at my current hoster and I always get errors with class constants in my code. Apparently, it's not allowed to define array constants. I changed the constant to a static variable to make it work. Now I get this syntax error:

    syntax error, unexpected '.', expecting ']'

I try to define strings that consist of concatenated constants.

public static $arr = [KEY_ONE => "string " . MyClass::CONSTANT . " string"]

is this possible or do all constants have to be static variables now?

2条回答
何必那么认真
2楼-- · 2019-09-22 04:30

if you are making array try like this:

public static $arr = array("KEY_ONE" => "string " . MyClass::CONSTANT . " string");
查看更多
聊天终结者
3楼-- · 2019-09-22 04:43

In the variable declaration you cannot do operations. Neither concatenation nor math operations.

You can do it in construct method;

public static $arr = [];

public function __construct(){
  self::$arr = [KEY_ONE => "string " . MyClass::CONSTANT . " string"];
}
查看更多
登录 后发表回答