hi shendz, welcome to the forums
shendz wrote:hi guys,
i am new to php and wonder why code below returns syntax error
Code: Select all
class test_array {
public static $an_array=array(
"first"=>"this is first",
"second"=>"this "."is "."second"
);
}
print test_array::$an_array["second"];
It's not allowed to use expressions (i.e. operators and function calls) in static/constant initializers. The workaround is rather ugly and based on the fact, that unlike class constants, define() does allow expressions:
Code: Select all
// this does NOT work
class A {
const foo = 2 + 2;
}
// this works
define('_foo', 2 + 2);
class B {
const foo = _foo;
}
Static class members can be initialized in the constructor or using dedicated function:
Code: Select all
class A {
static $foo;
function __construct() {
if(!isset(self::$foo))
self::$foo = 2 + 2;
}
}
new A;
In general, it's better to avoid complex constant expressions.