Stemar
Stemar

Reputation:

Can a PHP class property be equal to another class property?

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?

Upvotes: 5

Views: 2429

Answers (3)

Stemar
Stemar

Reputation:

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

Upvotes: 0

notruthless
notruthless

Reputation: 550

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?

Upvotes: 3

Paolo Bergantino
Paolo Bergantino

Reputation: 488644

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 ) 

Upvotes: 7

Related Questions