views:

445

answers:

3

I want to do this:

class MyClass {
   var $array1 = array(3,4);
   var $array2 = self::$array1;
}

and $array2 doesn't work.

Do you have a solution/trick to make a class property equal to another class property?

Thanks.

+4  A: 

According to the PHP Manual:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

What you COULD do is:

class MyClass {
    var $array1 = array(3,4);
    var $array2 = array();

    function MyClass() {
        $this->array2 = $this->array1;
    }
}

The function MyClass (or __construct if you are in PHP5) will be called every time a new object is created, so any instances of MyClass would have an array2 property that has the same value as its array1 property.

$myclass = new MyClass();
print_r($myclass->array1); // outputs Array ( [0] => 3 [1] => 4 ) 
print_r($myclass->array2); // outputs Array ( [0] => 3 [1] => 4 )
Paolo Bergantino
+3  A: 

I'm new to PHP, but the answer from Paolo seems to be just initializing the values to be the same in the constructor, but that doesn't actually make both variables reference the same content. How about this:

class MyClass {
    var $array1 = array(3,4);
    var $array2 = array();

    function MyClass() {
        $this->array2 = &$this->array1;
    }
}

$myclass = new MyClass();
print_r($myclass->array1); // outputs Array ( [0] => 3 [1] => 4 ) 
print_r($myclass->array2); // outputs Array ( [0] => 3 [1] => 4 )
echo "<br />";
$myclass->array1[0] = 1;
$myclass->array2[1] = 2;
print_r($myclass->array1); // outputs Array ( [0] => 1 [1] => 2 ) 
print_r($myclass->array2); // outputs Array ( [0] => 1 [1] => 2 )

With the addition of the reference, both class property values change when either is changed. Am I missing something?

notruthless
I didn't get the impression from his question that he wanted them referenced to one another, just that he wanted them to originally be the same.
Paolo Bergantino
Oh, OK, then I misunderstood the question!
notruthless
No, not necessarily. Maybe I did. :) It's a good answer.
Paolo Bergantino
A: 

Both your answers, Paolo and notruthless, are excellent, thank you very much!

If I want the two properties to keep in sync:

function MyClass() {
    $this->array2 = &$this->array1;
}

If I want the two arrays to have identical values initially but then want to modify them individually, I remove the '&':

function MyClass() {
    $this->array2 = $this->array1;
}
Yup! Sounds about right.
Paolo Bergantino
Just make your code PHP 5 friendly naming your constructor function simply __construct() instead of MyClass().
Michał Rudnicki