0

is it possible to copy a variable like this this?

class Colours {
   var $var = "one";
   var $var2 = array('something', $var);
}
1
  • Unrelated side note: PHP 4 is pretty old; you should be using the PHP 5 OOP syntax unless you're maintaining legacy code. Commented Mar 22, 2010 at 10:29

3 Answers 3

6

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

1 Comment

This won't work because at the time of class declaration, there is no $this present yet.
0
 <?php
     $var = "one";
     $var2 = array('something', $var);
    print_r($var2)
    ?>


 I got the following output 



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

1 Comment

He means in a class. In which it would be $this->var.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.