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 does not work.

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

Thanks.

+3
source share
3 answers

In accordance with PHP Manual:

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

What do you PRAY:

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 MyClasswill have a property array2that has the same value as its property array1.

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

PHP, Paolo, , , , , , :

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 )

. - ?

+3

Both of your answers, Paolo and ruthless, excellent, thank you very much!

If I want two properties to be kept in sync:

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

If I want both arrays to have the same values ​​initially, but then want to individually change them, I delete '&':

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

Source: https://habr.com/ru/post/1702198/


All Articles