rizxta
rizxta

Reputation: 3

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

Upvotes: 0

Views: 175

Answers (3)

muruga
muruga

Reputation: 2122

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


 I got the following output 



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

Upvotes: 0

Andy Shellam
Andy Shellam

Reputation: 15545

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

Upvotes: 6

Adam Hopkinson
Adam Hopkinson

Reputation: 28793

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

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

Upvotes: 2

Related Questions