Object Identity, Comparison, Cloning and Serialization

13.Object Identity, Comparison, Cloning and Serialization

M

In this chapter

We'll learn how PHP really stores objects — variables hold handles, so assigning an object doesn't copy it — the difference between identity (===) and equality (==), how clone makes a shallow copy and __clone a deep one, and how serialize() and json_encode() turn objects into text — plus why unserializing user input is dangerous.

16–18 min

The Problem in Real Life

Clare wants to move her Friday 9:30 haircut to 11:00. Mia's reschedule code keeps the old booking for the history log and makes the new one from it: $moved = $booking; $moved->start = "11:00";.

The history log now says Clare's original booking was at 11:00 too, and the 9:30 slot shows as free on Friday and booked at 11:00 twice. Changing $moved changed $booking.

M

With arrays, $copy = $day gave me a copy. Why doesn't it work for objects?

Mia

Copying a Value vs. Copying a Handle

Two names, one object

Assigning an object copies a handle to it, not the object. Both variables now reach the same booking.

Same, or just equal?

Two bookings with the same details are equal (==). Only one booking is the same booking (===).

A real copy

clone makes a new object — but only one level deep, unless the class says otherwise.

Object Identity, Comparison, Cloning and Serialization

What a variable really holds: this chapter answers the questions Act 03, Act 08 and Act 09 left open about objects:

  • Object handles: why assigning or passing an object never copies it.
  • Identity and equality: === versus == for objects.
  • Cloning: clone, shallow copies and __clone().
  • Serialization: turning objects into text and back, safely.

Variables hold handles: an array is a value (Act 08): $copy = $day; gives a second, separate array. An object is different. new Booking(...) creates the object somewhere in memory and gives you a handle to it — a small ID that points at it. A variable holds the handle, not the object. $moved = $booking; copies the handle, so both variables point at the same booking, and changing it through either one changes it for both. That's Mia's bug. The same happens when you pass an object to a function or store it in an array or a property: the function receives a copy of the handle and can change the object (Act 09 promised this), which is exactly what made chapter 11's shared Customer work. But if the function assigns a new object to its parameter, the caller's variable still points at the old one — it's a copy of a handle, not a reference (&, Act 03). The diagram below shows the difference between copying an array and copying an object handle.

$moved = $booking copies the handle, not the object

$booking

handle #1

$moved

handle #1 (a copy of the handle)

both point at the same object

Booking object #1

customer: Clare Lefèvre · start: 11:00

compare

Arrays are different

$copy = $day gives a second, separate array (Act 08)

Mia's bug: assignment copies the handle
<?php
declare(strict_types=1);
class Booking
{
public function __construct(public string $customer, public string $start) {}
}
$booking = new Booking("Clare Lefèvre", "09:30");
$moved = $booking; // NOT a copy: the same object
$moved->start = "11:00";
echo $booking->start, " ", $moved->start, "\n"; // 11:00 11:00 — the original moved too
Handles in functions: change yes, replace no
<?php
declare(strict_types=1);
class Booking
{
public function __construct(public string $start) {}
}
function moveTo(Booking $b, string $start): void
{
$b->start = $start; // changes the caller's object
}
function replace(Booking $b): void
{
$b = new Booking("15:00"); // only this function's copy of the handle changes
}
$booking = new Booking("09:30");
moveTo($booking, "11:00");
replace($booking);
echo $booking->start, "\n"; // 11:00

Identity and equality: $a === $b on objects asks about identity: are these two handles pointing at the same object? $a == $b asks about equality: are they of the same class, with equal property values (compared with ==, one by one)? Two separate bookings for Clare at 9:30 are equal but not identical. Use === to ask "is this the same booking?" and == only for value objects like Money, where equal values mean the same thing. spl_object_id($object) gives the number behind the handle, handy while debugging. (Objects can also be compared with < and >, property by property, but the result is rarely meaningful — compare a property instead.)

Identity (===) and equality (==)
<?php
declare(strict_types=1);
class Booking
{
public function __construct(public string $customer, public string $start) {}
}
$a = new Booking("Clare Lefèvre", "09:30");
$b = new Booking("Clare Lefèvre", "09:30"); // same details, separate object
$c = $a;
var_dump($a == $b); // bool(true): equal properties
var_dump($a === $b); // bool(false): not the same object
var_dump($a === $c); // bool(true): the same object
var_dump(spl_object_id($a) === spl_object_id($c)); // bool(true)

clone: $moved = clone $booking; creates a new object with the same property values: a real copy, with its own identity. That's the fix for the reschedule. But the copy is shallow: properties holding other objects copy their handles, so the clone shares those objects with the original. For a shared Customer that's right (chapter 11's aggregation), but for parts the booking owns (composition), like its list of lines, both bookings would now share and change the same parts. A class fixes that with a __clone() method, which PHP runs on the new copy right after cloning: in it, the class clones its own parts too — a deep copy where it matters. C++ solves the same problem with copy constructors (chapter 3); PHP uses clone plus __clone(). For readonly objects, PHP 8.5's clone($this, [...]) makes a changed copy (chapter 6). The diagram below compares the two kinds of copy.

Shallow clone vs. deep clone

Original booking

start 09:30 · lines → Lines object A

two ways to copy

clone (shallow)

new booking · lines → the SAME Lines object A

clone + __clone() (deep)

new booking · lines → its own Lines object B

result

Adding a line to the copy changes the original

shared part

Adding a line to the copy leaves the original alone

owned part copied

clone is shallow; __clone() makes it deep
<?php
declare(strict_types=1);
class Lines
{
public array $items = ["Haircut"];
}
class Booking
{
public Lines $lines;
public function __construct(public string $start)
{
$this->lines = new Lines(); // composition: the booking owns its lines
}
}
class SafeBooking extends Booking
{
public function __clone(): void
{
$this->lines = clone $this->lines; // runs on the copy: give it its own lines
}
}
$original = new Booking("09:30");
$moved = clone $original; // a new booking...
$moved->start = "11:00";
$moved->lines->items[] = "Hot towel"; // ...but the SAME Lines object
echo $original->start, " ", count($original->lines->items), "\n"; // 09:30 2
$safe = new SafeBooking("09:30");
$safeMoved = clone $safe;
$safeMoved->lines->items[] = "Hot towel";
echo count($safe->lines->items), "\n"; // 1: deep copy, the original is untouched

Serialization: serializing turns an object into a string, so it can be stored in a file, a cache or a session (Act 17) and turned back later. serialize($booking) produces a PHP-specific string that includes the class name and every property, private ones too, and unserialize($text) rebuilds the object. Classes can control this with __serialize() and __unserialize() (Act 12). One rule is critical: never unserialize text that came from users (a cookie, a form, an API). A crafted string can create objects of any class in your project and run their magic methods — an attack called PHP object injection (Act 20). For data that crosses a trust boundary, use JSON: json_encode($object) turns its public properties into JSON (private ones are left out; JsonSerializable controls it, Act 19). If you must unserialize, pass ["allowed_classes" => false] or a list of allowed classes. The table below sums up the chapter.

Table — Copying and comparing objects
CodeWhat happens
$b = $a;Copies the handle: one object, two variables
f($a)The function gets a copy of the handle: it can change the object
$b = clone $a;A new object; properties copied one level deep (shallow)
__clone()Runs on the copy after clone: deep-copy owned parts here
$a === $bIdentity: the same object?
$a == $bEquality: same class and equal property values?
serialize($a) / unserialize($s)PHP text format with class names — never unserialize user input
json_encode($a)Public properties as JSON — safe to exchange
serialize() and json_encode()
<?php
declare(strict_types=1);
class Booking
{
public function __construct(public string $customer, private string $internalNote = "VIP") {}
}
$booking = new Booking("Tom Hart");
$text = serialize($booking);
echo $text, "\n";
// O:7:"Booking":2:{s:8:"customer";s:8:"Tom Hart";s:21:"BookinginternalNote";s:3:"VIP";}
// (private names carry hidden marker bytes, so the exact text varies)
$back = unserialize($text, ["allowed_classes" => [Booking::class]]);
var_dump($back == $booking); // bool(true)
echo json_encode($booking), "\n"; // {"customer":"Tom Hart"} — public properties only

Key Takeaway

Variables hold handles to objects, so assigning or passing an object shares the same object — unlike arrays, which are copied; a function can change an object it receives, but reassigning the parameter doesn't affect the caller. === checks identity (the same object); == checks equality (same class, equal properties). clone makes a shallow copy; __clone() deep-copies the parts the object owns. serialize()/unserialize() store objects as text — never unserialize user input (object injection); use JSON, which exports public properties.

Why This Matters

"Two variables, one object" is the source of some of the most confusing bugs in object-oriented code: a change in one place shows up somewhere else. Knowing that variables hold handles — and when to clone — makes those bugs obvious, and explains why sharing a Customer between bookings works at all.

Serialization is how objects survive between requests (sessions, caches, queues), and unserialize() on user input is one of PHP's classic remote-code-execution holes. Knowing the safe default — JSON for anything from outside — protects BookBay long before the security Act.

Rescheduling now clones the booking, and Clare's history shows 9:30, then 11:00. Sunday is almost over: BookBay's code has Booking, Customer, Barber and Service classes, private data, a Notifier interface and injected dependencies. One job is left for this Act: put them all together into one small booking desk, with every rule in the right class. That's the checkpoint.