Jump to content

Question about object cloning


eldan88

Recommended Posts

Hey guys. I have been working with object cloning, and I am little confused on the difference when using the

$clone_object = clone $object and having the __clone() method in the actual class?

 

I tried to read through the PHP documentation, and it mentioned something about a "GTK window"? What is a GTK window?

 

Your help is always appreciated!

Link to comment
https://forums.phpfreaks.com/topic/282234-question-about-object-cloning/
Share on other sites

Don't worry about that (unless you're actually using GTK).

 

Cloning happens one way or another. You can provide __clone() to execute some code after the cloning happens.

class NormalClone {
}

$a = new NormalClone();
print_r($a);
$b = clone $a;
print_r($b);
class SpecialClone {
	public function __clone() { echo "Special clone"; }
}

$a = new SpecialClone();
print_r($a);
$b = clone $a;
print_r($b);

Remember that when cloning an object the object references it holds are left untouched.

 

class Woll {
  private $thickness;
  ..
}

class Sheep {
  private $woll;
  
  public function __construct() {
    $this->woll = new Woll(3);
  }
  
  public function setWollThickness($thickness) {
    ..
  }
}
$sheep = new Sheep;
$dolly = clone $sheep;
$dolly->setWollThickness(6);
echo $sheep->getWollThickness(); // 6
echo $dolly->getWollThickness(); // 6
To avoid this you need to clone the object references inside your object aswell:

 

public function __clone() {
  $this->woll = clone $this->woll;
}
Whom in turn would have to do the same thing etc..

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.