PHP object assign alway by reference

Different from what we discuss before about regular variable type, object assignment always by reference:

class A {
        public $a = 'a';
}

$a = new A();
$b = clone $a;
$c = $a;
$b->a = 'b';
echo $a->a, "\n";
$c->a = 'c';
echo $a->a, "\n";

Output:

a
c

We use clone to make a copy of object. Please note that default clone operation is shallow copy. You have to overload the __clone method if you want deep copy of the object.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Share/Bookmark

Leave a Reply