开发者

Error when initiating an array using another array in PHP class

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.


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);
    }
}
?>


Try put those array-initialazing to the constructor of the test class


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜