18

This thing is bugging me a lot. I'm getting Parse error: syntax error, unexpected '.', expecting ',' or ';' at this line

public static $user_table = TABLE_PREFIX . 'users';

TABLE_PREFIX is a constant created by define function

Tejas Jadhav
  • 693
  • 2
  • 10
  • 11
  • echo the constant and see if its getting the value... – sree Jun 10 '12 at 14:09
  • Probably the problem is in your constant so you might put that definition up for us to see as well. – Alan Moore Jun 10 '12 at 14:11
  • possible duplicate of [Attribute declarations in a class definition can only be constant values, not expressions.](http://stackoverflow.com/questions/2671928/workaround-for-basic-syntax-not-being-parsed) – mario Jun 11 '12 at 19:02
  • @sree If I echo TABLE_PREFIX and users separately, it works. But cannot concatenate both of them – Tejas Jadhav Jun 11 '12 at 20:00
  • possible duplicate of [Parse error: syntax error, unexpected '(', expecting ',' or ';' in](http://stackoverflow.com/questions/11313051/parse-error-syntax-error-unexpected-expecting-or-in) – nickb Aug 07 '12 at 21:25
  • Definitely shouldn't be closed as too localised - helped me, and I'm in *the future!!!* dealing with an ancient PHP version. – Hippyjim May 21 '19 at 09:09

2 Answers2

22

Static class properties are initialized at compile time. You cannot use a constant TABLE_PREFIX to concatenate with a string literal when initializing a static class property, since the constant's value is not known until runtime. Instead, initialize it in the constructor:

public static $user_table;

// Initialize it in the constructor 
public function __construct() {
  self::$user_table = TABLE_PREFIX . 'users';
}

// If you only plan to use it in static context rather than instance context 
// (won't call a constructor) initialize it in a static function instead 
public static function init() {
  self::$user_table = TABLE_PREFIX . 'users';
}

http://us2.php.net/manual/en/language.oop5.static.php

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

Update for PHP >= 5.6

PHP 5.6 brought limited support for expressions:

In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
8

The dot is a string concatenation operator. It's a runtime function, so it can't be used to declare a static (parsetime) value.

troelskn
  • 115,121
  • 27
  • 131
  • 155