PHP 7 interview question · Most asked

What is the difference between assigning an object and cloning it?

Summary

Assigning an object copies the handle, so both variables refer to the same object; clone creates a new object with copied properties (shallow), and calls __clone() for customization.

Longer Answer

With a shallow clone, nested objects are still shared. Implement __clone() to deep-copy them: $this->address = clone $this->address;. Immutable objects avoid this problem entirely.

Key Points

  • Assignment shares the object
  • clone is shallow
  • __clone() for deep copies
  • Immutability sidesteps aliasing

More most-asked PHP 7 questions

← All PHP 7 questions