I try to initialize an array using another array in php class. Here is the code:
<?php class test
{
var $nodeDomain = array
("gd88" =>"10.10.104.88", "gd02" =>"10.10.104.2");
var $node = array
("x86-mysql" =>$nodeDomain['gd88'],
"x86-hbase" =>$nodeDomain['gd02']);
function show ()
{
print_r($node);
}
}
?>
I got this error: Parse error: syntax error, unexpected T_VARIABLE in /root/workspace/php/array.php on line 6
But when I run the code without using class it works fine. I mean I run the following code:
var $nodeDomain = array
("gd88" =>"10.10.104.88", "gd02" =>"10.10.104.2");
var $node = array
("x86-mysql" =>$nodeDomain['gd88'],
"x86-hbase" =>$nodeDomain['gd02']);
I am not quite clear about the difference of php class and php script. Can anyone explain this?
Thanks.
Try put those array-initialazing to the constructor of the test class
You can not use another variables when declaring class members. Try to initialize them in constructor.
<?php class test
{
var $nodeDomain;
var $node;
public function __construct() {
$this->nodeDomain = array("gd88" =>"10.10.104.88", "gd02" =>"10.10.104.2");
$this->node = array("x86-mysql" =>$this->nodeDomain['gd88'],
"x86-hbase" =>$this->nodeDomain['gd02']);
}
function show ()
{
print_r($node);
}
}
?>
You just can't reference variables in the field declarations. Where should this variable come from anyway? There are no local variables and no way to position a global statement. (Of course superglobals could work but that's obviously not implemented ;-)) Instead you can do something like this:
<?php class test
{
var $nodeDomain = array
("gd88" =>"10.10.104.88", "gd02" =>"10.10.104.2");
var $node;
function __construct()
{
$this->node = array
("x86-mysql" =>$nodeDomain['gd88'],
"x86-hbase" =>$nodeDomain['gd02']);
}
function show ()
{
print_r($node);
}
}
?>
Beware that $nodeDomain must be in the scope of the constructor somehow. Either it is a global variable, so you need a global $nodeDomain
statement before the assignment or you can pass $nodeDomain as constructor argument.