Page 1 of 1
setting array value with string operation
Posted: Mon Mar 26, 2007 6:08 am
by shendz
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"];
$an_array["first"] is a no problem, but $an_array["second"] is a problem because i assign combined string as the value
can't i do that? is there any other way?
thank you
Posted: Mon Mar 26, 2007 6:30 am
by shendz
oh ya, and i also think of a solution like below but it doesnt work either
Code: Select all
class test_array {
public static $an_array=array(
"first"=>"this is first",
"second"=>sprintf(
"%s %s %s",
"this",
"is",
"second")
);
}
print test_array::$an_array["second"];
why sprintf here won't solve the problem? i thought at least operator => takes value from a function and sprintf is a function just like array()
this idea came up to me because i know i can use array as an array value like if i want to make multidimensional array
Code: Select all
class test_array {
public static $an_array=array(
"first"=>"this is first",
"second"=>array(
"another_first"=>"this is also first",
"another_second"=>"this is second"
)
);
}
Posted: Mon Mar 26, 2007 6:30 am
by aaronhall
When you're referring to object properties, don't include the dollar-sign; use test_array::an_array["second"] instead.
Re: setting array value with string operation
Posted: Mon Mar 26, 2007 6:47 am
by stereofrog
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.
Posted: Mon Mar 26, 2007 7:10 am
by shendz
thank you very much for the explaination!