A Rigorous Study of Deep Copy in PHP

Written by AbiusX on . Posted in Computer, Development, Hacks, PHP, Security, Software Engineering

In this post, we will go through the process of deep copying a PHP variable in user land (i.e., in pure PHP) step by step, describing the challenges facing every step, resolving them and going forward.

(TL;DR: check this Github gist for the final solution)

The Challenges

There are three particular challenges for solving the deep copy problem in PHP:

  1. Some things simply can not be copied (e.g., resources like file handles, and objects like MySQLi instances)
  2. References are invisible in PHP. They can only be set in PHP, and accessing them will automatically dereference them.
  3. Everything is deep copied by default in PHP, except objects. They are shallow copied.

Now we will tackle these challenges one by one. Let's start with the one liner solution:

function deep_copy(&$variable) { return unserialize(serialize($variable)); }

This one-liner, is the best easy deep copy solution we can find. It deep copies objects, handles references and even circular references (as long as all referenced targets are available in $variable, otherwise their value will be used), and is pretty fast and straightforward.

The only problem with this method will be visible when one takes a look at the internal PHP code: