开发者

variable inside a variable in a php class

is it possible to copy a variable like this this?

class Colours {
   var $var = "one";
   var $var2 = array('something'开发者_运维问答, $var);
}


The preferable way is to do this in the constructor of the Colours class. I'm not sure in PHP, but in other languages the order of initialisation of the variables should not be relied upon.

class Colours 
{ 
    private $var;
    private $var2;

    public function __construct()
    {
        $this->var = "one";
        $this->var2 = array('something', $this->var);
    }
}


You'd need to use $this->var to access the variable

class Colours {
   var $var = "one";
   var $var2 = array('something', $this->var);
}


 <?php
     $var = "one";
     $var2 = array('something', $var);
    print_r($var2)
    ?>


 I got the following output 



     Array 
    (
            [0] => something
            [1] => one
    )
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜