0
0
PHPprogramming~5 mins

__clone for object copying in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the __clone method in PHP?
The __clone method is called automatically when an object is cloned using the clone keyword. It allows you to customize the copying process, such as resetting properties or cloning nested objects.
Click to reveal answer
beginner
How do you create a copy of an object in PHP?
You create a copy of an object by using the clone keyword. For example: $copy = clone $original; This triggers the __clone method if it exists.
Click to reveal answer
intermediate
What happens if you don't define a __clone method in your class?
If __clone is not defined, PHP performs a shallow copy of the object, copying all properties as they are. Nested objects inside properties will still reference the same objects.
Click to reveal answer
intermediate
Why might you need to implement __clone when your object has properties that are objects?
Because PHP does a shallow copy by default, nested objects inside properties will not be cloned automatically. Implementing __clone lets you clone those nested objects too, so the copy is independent.
Click to reveal answer
beginner
Show a simple example of a __clone method that resets a property after cloning.
Example:<br><pre>class User {
  public $name;
  public $id;
  public function __clone() {
    $this->id = null; // reset id on clone
  }
}</pre>
Click to reveal answer
What keyword is used to copy an object in PHP?
Aduplicate
Bcopy
Cclone
Dnew
What does PHP do by default when cloning an object without a __clone method?
APerforms a shallow copy of the object
BPerforms a deep copy of the object
CThrows an error
DCopies only public properties
When is the __clone method called?
AWhen an object is cloned using <code>clone</code>
BWhen an object is created with <code>new</code>
CWhen an object is destroyed
DWhen a property is accessed
Why might you want to reset a property inside __clone?
ATo increase performance
BTo avoid sharing unique identifiers between original and clone
CTo prevent cloning
DTo delete the object
Which of these is true about cloning nested objects without __clone?
ANested objects become null
BNested objects are cloned automatically
CNested objects are deleted
DNested objects are shared between original and clone
Explain how the __clone method helps when copying objects with nested objects.
Think about what happens to objects inside properties when you clone.
You got /5 concepts.
    Describe a situation where you would want to reset a property inside the __clone method.
    Consider properties that should not be copied exactly.
    You got /4 concepts.