开发者

variable inside a variable in a php class

开发者 https://www.devze.com 2022-12-24 05:06 出处:网络
is it possible to copy a variable like this this? class Colours { var $var = \"one\"; var $var2 = array(\'something\'开发者_运维问答, $var);

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

精彩评论

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