开发者

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开发者_Go百科 $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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜