4

Possible Duplicate:
Syntax error while defining an array as a property of a class

I'm trying to do the following:

final class TestClass {
    public static $myvar = 10*10; //line 3
    //rest of code...
}

but i'm getting this error: syntax error, unexpected '*', expecting ',' or ';' [line 3]

why isn't this possible? of course, if i change 10*10 to 100, everything works ok. Is it not allowed to init a static variable with a math calculation? Not possible with any way?

Community
  • 1
  • 1
CdB
  • 4,738
  • 7
  • 46
  • 69
  • 2
    Alternatively, one can create a static getter function: http://stackoverflow.com/a/7785213/1335996 – psycho brm Mar 13 '13 at 15:46
  • As of PHP 5.6 `static` allows to use scalar expresions thus the code in your question is fully workable in PHP >= 5.6. A scalar expressions may include integers, floats, strings and constants combined with math, bitwise, logic, concatenation, ternary and comparison operators. For example the following definitions are now correct inside of your class: `public static $bar = "This class name is ".__CLASS__;` `public static $baz = 8 >> 1;` `public static $bat = 10+3*2;` – Alex Myznikov Feb 19 '17 at 20:09

4 Answers4

11

From php docs

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.

MikeSW
  • 16,140
  • 3
  • 39
  • 53
9

i think you have to create a static init method on your class like this

final class TestClass {
    public static $myvar = null; //line 3

    public static function init() {
    self::$myvar = 10*10;
    }
    //rest of code...
}

and call the init first like this

TestClass::init();

thats the static-way

silly
  • 7,789
  • 2
  • 24
  • 37
2

No. Class properties (even static ones) are only allowed to be initialized by values, not expressions.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
2

No it's not possible to do anything in static/non static initialization. You can only set simple variables (protected $_value = 10;) or build arrays (protected static $_arrr = array("key" => "value")).

You can create az Initialize static method and an $_isInitialized static field to check before you reinitialize your class but you will have to call the Initialize method somehow (in constructor, same factory implementation and so on).

Peter Kiss
  • 9,309
  • 2
  • 23
  • 38