5

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?

2
  • 3
    Alternatively, one can create a static getter function: stackoverflow.com/a/7785213/1335996 Commented Mar 13, 2013 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; Commented Feb 19, 2017 at 20:09

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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

Comments

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.