Jump to content

Question about object cloning


eldan88
Go to solution Solved by requinix,

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
Share on other sites

  • Solution

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);
Edited by requinix
Link to comment
Share on other sites

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.. Edited by ignace
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.