开发者

The object assignment doesn't make sense in PHP OOP

I was tested and I got this wrong but this doesn't make sense:

class myClass
{
  public $x;

  function myMethod()
  {
    echo $this->x;
  }
}

$a = new myClass();
$a->x = 10;
$b = $a;
$b->x = 20;
$c开发者_Python百科 = clone $b;
$c->x = 30;

$a->myMethod();
$b->myMethod();
$c->myMethod();

My intuition would be 102030 but the result is actually 202030!!! What happened to 10?!?! Shouldn't the variable of $a be left alone? I thought all objects are independent and would not be updated unless it has direct reference set by the ampersand (=&)?


In $b = $a;, only the object reference is being copied, not the object.

When you use clone, however, the object is indeed being copied, so $c = clone $b, creates both a new object (referenced by $c) and a new reference ($c).

In $b =& $a;, both symbols $a and $b would point to the same reference, that is, not even the reference would be copied (and therefore an assignment to $b of, say, an integer, would also affect the value of $a).

To sum up, there are two indirections here: from the symbol to the "zval" (in the case an object reference) and from the object reference to the object itself (i.e., to a portion of memory where the actual object state is stored).


From the PHP manual:

When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.


PHP uses references for objects. So when you create a new one

$a = new myClass();

PHP doesn't actually store it in $a, it just puts the reference there. Now you copy the reference:

$b = $a;

When you modify the object pointed by $a, you also modify the one pointed by $b because they point to the same thing.


As $a represents a reference to an object and not the object itself, you are assigning the reference to $b. Now, $a and $b reference the same object, when you manipulate the object referenced by $b, the changes get reflected accessing it via $a as well.


Objects are handled by reference, and references are aliases on assignment. So after you say $b = $a, both variables refer to the same object.

The value/reference distinction is fundamental in many "modern" OO languages: values are copied, references are aliased. It is perhaps unfortunate that the syntax of the language does not always make it obvious which semantics the variable obeys at any given point.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜