Reputation: 1499
I'm trying to assign the output of a static method to a static variable in PHP, but always get the error.
Parse error: syntax error, unexpected T_FUNCTION in ./MyClass.php on line 8
class MyClass
{
public static function myMethod()
{
return array('a' => 'b'); //some array
}
public static $myarr = self::myMethod();
}
I've also tried...
class MyClass
{
public static $myarr = call_user_func(function
{
return array('a' => 'b'); //some array
}
);
}
...but I get the same error on line 3. I've gone through this a bunch of times and I don't see any typos, so I'm not sure what I'm doing wrong. Any ideas?
Upvotes: 0
Views: 211
Reputation: 212502
You cannot assign a value to a static variable by calling a function at declaration time.
Quoting from the manual (my emphasis):
They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value -- that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
Upvotes: 4
Reputation: 32127
Change:
public static myMethod()
To:
public static function myMethod()
Upvotes: 1