string concatenation with constants

2019-09-22 04:17发布

问题:

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?

回答1:

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"];
}


回答2:

if you are making array try like this:

public static $arr = array("KEY_ONE" => "string " . MyClass::CONSTANT . " string");