简体   繁体   中英

Pass an object into another class by reference

I did see this question but it doesn't fully answer the question I have.

If I do this:

$obj1 = new ObjectOne();

and then this:

$obj2 = new ObjectTwo($obj1);
$obj2->someFunction();

Where someFunction() modifies the attributes of the object passed into it, will both $obj1 and $obj2->passedInObject both in effect be updated?

I tried the following code, and it works as expected. The var in MyObject gets incremented in the original object.

<?php 
class MyObject {
     public $var;
}

class MyObjectTwo {
    public $objVar;
    function __construct($aObj1) {
        $this->objVar = $aObj1;
    }

    public function someFunction() {
        $this->objVar->var++;
    }
}

$obj1 = new MyObject();
$obj1->var = 5; // Originally set to 5

$obj2 = new MyObjectTwo($obj1);
$obj2->someFunction();
echo $obj1->var; // Prints 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM