0

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?

user1563232
  • 361
  • 3
  • 17
  • Maybe a question of operator preference, did you try putting parentheses around the concatenation? Like in `[KEY_ONE => ("string " . MyClass::CONSTANT . " string")]`. – syck Jun 23 '16 at 10:17

2 Answers2

3

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"];
}
David Rojo
  • 2,337
  • 1
  • 22
  • 44
  • 1
    Or some sort of an `init()` method if you don't want to instantiate an object. – jeroen Jun 23 '16 at 10:25
  • This limitation of PHP 5.4 is informed here: https://www.php.net/manual/en/language.oop5.properties.php (see Example #1 property declarations). The possibility of doing concatenations, in class member variables, was introduced as of PHP 5.6. – aldemarcalazans Jul 31 '20 at 17:06
0

if you are making array try like this:

public static $arr = array("KEY_ONE" => "string " . MyClass::CONSTANT . " string");
Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90