Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 147 ยท Object-Oriented PHP

Comparing, Copying and Serializing Objects

Learn how PHP compares objects with == and ===, shallow versus deep copies with clone and __clone, the dangers of unserialize, and JSON with JsonSerializable.

Integers and strings are simple: 5 is 5, and copying a string gives you an independent string. Objects are different. A variable doesn't contain an object; it contains a handle that points to one. That one fact explains how PHP compares objects, why $b = $a doesn't copy anything, why clone sometimes copies less than you expect, and why turning objects into strings and back needs care.

This lesson covers comparing objects (== versus ===), copying them (shallow and deep clones with __clone()), turning them into strings with serialize() and why unserialize() on untrusted data is dangerous, and finally the safe, portable alternative: JSON with the JsonSerializable interface.

It builds on classes and objects, magic methods and readonly objects.

Handles: assignment doesn't copy

A quick refresher, because everything else depends on it. Assigning an object to another variable, passing it to a function or storing it in an array copies the handle, not the object. Both variables then point to the same object:

PHP Two variables, one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is 5, bool(true), 6 and 6 0. Reassigning $b at the end doesn't affect $a at all, because it just points $b somewhere else. Arrays behave differently: assigning an array copies it (lazily, with copy-on-write), so arrays of scalars are independent after assignment.

Comparing objects: == versus ===

PHP has two equality operators, and on objects they mean very different things:

  • === (identity) is true only if both operands are the same object, the same instance.
  • == (equality) is true if both are instances of the same class and all their properties are equal when compared with ==.
PHP Identity versus equality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last two lines show why == on objects can be surprising: it compares properties loosely, so '1' equals 1 and true equals 1. With typed properties these accidents mostly go away, because a Point with int $x can't hold '1'.

== is also recursive: a property holding another object is compared with == too. That makes it fine for small value objects, but it can be slow for large object graphs, and objects that refer to each other in a loop make PHP stop with Nesting level too deep - recursive dependency?.

Write an equals() method

For anything that matters, don't rely on ==. Write an explicit equals() method that defines what "the same value" means for your class. Maybe two Money objects are equal only if the amount and currency match exactly, and two email addresses are equal regardless of upper and lower case:

PHP An explicit equals method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Note the trap with in_array(..., true): strict mode uses ===, which on objects checks identity, so it doesn't find a different Money with the same value. array_any() (PHP 8.4) with your own equals() says exactly what you mean. Libraries such as test frameworks also compare objects by value (assertEquals), which is a different operation from ===.

The ordering operators <, > and <=> also work on objects of the same class, comparing properties one by one in declaration order. It's rarely what you want; sort objects with usort() and an explicit comparison on the property you care about.

Copying objects with clone

To get a real copy, use clone. It creates a new object of the same class and copies every property's value into it:

PHP
$copy = clone $original;

The copy is a shallow copy. Scalars and arrays are copied, but a property that holds an object still holds the same handle, so the original and the copy share that inner object:

PHP A shallow copy shares inner objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The name and the tags array are independent after cloning, but the city changed to Bergen for both customers, because they share one Address object. That's rarely what someone writing clone intends.

Deep copies with __clone

After clone copies the properties, PHP calls the __clone() method on the new object. That's where you clone the inner objects that should not be shared, making a deep copy:

PHP Deep copy with __clone

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Now the original keeps Lisbon and quantity 1. Two details are easy to miss:

  • Arrays of objects need their elements cloned. Copying the array copies the handles inside it, so array_map(fn ($i) => clone $i, ...) is needed to clone each element.
  • __clone() can do other bookkeeping too, like the version counter above, resetting an ID or clearing a cache. Since PHP 8.3 it may also reinitialize readonly properties.

Not every inner object needs cloning. Immutable objects such as DateTimeImmutable, enum cases and your own readonly value objects can safely be shared, because nobody can change them. That's one more advantage of immutability: no deep-copy code at all.

Some objects can't be cloned: enum cases, generators, and classes that make __clone() private (often singletons). Trying throws an Error like Trying to clone an uncloneable object of class Generator.

serialize() and unserialize()

serialize() converts almost any PHP value, objects included, into a string. unserialize() turns that string back into an equal value. PHP uses it internally for sessions, and frameworks use it for caches and queued jobs:

PHP Serializing and restoring an object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The format is compact: O:8:"Settings":3:{...} means an object of the 8-character class Settings with 3 properties; s: is a string, i: an integer, a: an array. Protected and private property names are stored with extra null-byte markers, which is why their lengths look larger than the names. The restored object is a fresh instance with equal properties, so unserialize(serialize($x)) is a deep copy, but a slow one, so prefer __clone().

Why unserialize() on untrusted data is dangerous

unserialize() creates objects of any class named in the string and sets their properties to any values in the string. Then PHP calls their magic methods: __unserialize() or __wakeup() immediately, and __destruct() when the object goes away. An attacker who controls the string can therefore create objects of classes in your application or its libraries, with properties of their choosing, and trigger those methods.

That's called PHP object injection. Imagine a logging class whose destructor writes a buffer to a file named by a property:

PHP
class TempLog
{
    public string $file = '/tmp/app.log';
    public string $buffer = '';

    public function __destruct()
    {
        file_put_contents($this->file, $this->buffer);
    }
}

// A cookie or form field containing this string...
$payload = 'O:7:"TempLog":2:{s:4:"file";s:19:"/var/www/html/x.php";s:6:"buffer";s:23:"<?php system($_GET[c]);";}';

unserialize($payload); // ...writes a PHP backdoor into the web root

Real attacks chain together harmless-looking methods from popular libraries ("gadget chains"), and public tools generate payloads automatically. This has led to remote code execution in widely used applications.

The rules:

  • Never pass user-controlled data to unserialize(): not cookies, form fields, URL parameters, uploaded files or API payloads. Use json_decode() for data that crosses a trust boundary.
  • If you must unserialize stored data, restrict the classes: unserialize($data, ['allowed_classes' => [Settings::class]]). With 'allowed_classes' => false, every object becomes a harmless __PHP_Incomplete_Class, which is why the last line of the example printed bool(false).
  • When you store serialized data yourself (in a cache, for example), sign it with hash_hmac() and verify the signature before unserializing. See Hashing, Encryption and Random Numbers and Secure Coding.

unserialize() also emits a Warning and returns false for a malformed string, so check its result.

JSON with JsonSerializable

For data that leaves your PHP process, whether it goes to a browser, an API client, a file or another language, JSON is the right format. json_encode() turns an object into a JSON object containing its public properties only:

PHP JsonSerializable controls the JSON shape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Implementing JsonSerializable gives you full control: jsonSerialize() returns whatever should be encoded, usually an array. Here it hides the password hash, formats the date in a standard way, and relies on json_encode() writing backed enums as their values. Without the interface, json_encode() would output only the three public properties, and the date would be missing.

Decoding is safe precisely because it's limited: json_decode() returns arrays (with true) or stdClass objects, never instances of your classes, so no constructors or magic methods run. To get your objects back, build them explicitly, as Role::from() does above. Larger applications use a mapper or serializer library for that. The JSON lesson covers flags, error handling and json_validate() in detail.

Format Readable by Restores your classes Safe for untrusted input
serialize() PHP only yes, with all magic methods no
json_encode() every language no, you rebuild objects yourself yes
var_export() PHP (as code) via __set_state() no (it's code)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. $a = new Point(1, 2); $b = new Point(1, 2); What are $a == $b and $a === $b?

    == checks the same class with equal properties, which is true. === checks whether both are the same instance, which is false because there are two objects.
  2. 2. An object has a property holding another object. After $copy = clone $original; with no __clone(), what is true?

    clone makes a shallow copy. Object properties copy the handle, so both objects point to the same inner object until __clone() clones it.
  3. 3. On which object does PHP call __clone()?

    __clone() runs on the newly created copy, so $this in __clone() is the copy and you can replace its shared inner objects with clones.
  4. 4. Why is unserialize() on a cookie value dangerous?

    This is PHP object injection. Use json_decode() for untrusted data, or at least restrict allowed_classes.
  5. 5. A class implements JsonSerializable and jsonSerialize() returns ["id" => 7]. What does json_encode($obj) produce?

    When a class implements JsonSerializable, json_encode() encodes whatever jsonSerialize() returns instead of the public properties.

Summary

  • Variables hold handles to objects; assignment and argument passing share the object instead of copying it.
  • === on objects means the same instance; == means same class and loosely equal properties, compared recursively. Write an equals() method for real value comparisons.
  • clone makes a shallow copy: object properties (including objects inside arrays) are still shared.
  • __clone() runs on the copy; clone inner mutable objects there for a deep copy. Immutable objects can be shared safely.
  • serialize()/unserialize() store and restore PHP values, but never unserialize untrusted data: it enables object injection. Restrict allowed_classes and sign stored data.
  • JsonSerializable controls json_encode() output; json_decode() returns plain data, so rebuild objects explicitly.

Next: OOP Design Principles