开发者

testing references

echo 'test';

class createdclass {
    public $name;
}

class testc {
    function &testm(){
        $myvar =& new createdc开发者_运维百科lass();
        return $myvar;
    }
}

$testo = new testc();

$a =& $testo->testm();
$a->name = 'Douglas';

$b =& $testo->testm();
$b->name = 'Scott';

echo $a->name;
echo $b->name;

myvar is a reference to an object

a and b are references to the same object

I changed a, then I changed b, but a wasn't changed by b

Why?


In your code each call to testm() creates a new instance of createdclass. So $a and $b aren't the same object.


Ok, first off, you shouldn't use $myvar =& new .... It's a deprecated syntax and is completely unnecessary (Since there's nothing to reference to)...

Secondly, you don't need the =& operator in the lines $a =& $testo->testm(). The fact that the method returns a reference is good enough. Not to mention that objects are passed by reference by default anyway, so you really don't need those lines anyway. I put them in the method signature function &foo() mainly for readability (to show that we're expecting the return to be a reference)...

Third, the problem is what you're referencing. References bind to a variable. When you leave the scope, since $myvar is a local variable (and as such is garbage collected -- it is deleted -- when the method exits), the bound reference disappears. So if you want that to work, you need to persist that variable.

Here's one example that works:

class testc {
    protected $createdclass = null;
    public function __construct() {
        $this->createdclass = new CreatedClass();
    }
    public function &testm() {
        return $this->createdclass;
    }
}

$tester = new testc;
$a = $tester->testm();
$a->name = 'foo';
$b = $tester->testm();
echo $b->name; //displays "foo"...


in your example, a and b do not reference the same object because you create a new one in the testm() function.

here is a short example that might clarify things a little:

<?php

class createdclass {
    public $name;
}

$a = new createdclass();
$a->name = 'Douglas';

// make $b reference the same as $a, i.e. let $p point to the same content as $a
$b = &$a;
$b = new createdclass();
$b->name = 'Scott';

echo $a->name;
echo $b->name;

?>

this will output ScottScott

if you want to learn more about references in php i'd recommend to read References Explained in the php manual

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜