Skip to content

Commit a91336a

Browse files
committed
minor #22137 [VarExporter] Document DeepCloner for COW-friendly deep cloning (lacatoire)
This PR was merged into the 8.1 branch. Discussion ---------- [VarExporter] Document DeepCloner for COW-friendly deep cloning Fixes #22135 Commits ------- 510326a [VarExporter] Document DeepCloner for COW-friendly deep cloning
2 parents 9dfdb9c + 510326a commit a91336a

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

components/var_exporter.rst

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,54 @@ populated by using the special ``"\0"`` property name to define their internal v
177177
"\0" => [$inputArray],
178178
]);
179179

180+
Deep Cloning
181+
------------
182+
183+
.. versionadded:: 8.1
184+
185+
The ``DeepCloner`` class was introduced in Symfony 8.1.
186+
187+
The :class:`Symfony\\Component\\VarExporter\\DeepCloner` class deep-clones PHP
188+
values while preserving PHP's copy-on-write semantics for strings and arrays.
189+
Unlike ``unserialize(serialize())``, it does not reallocate strings and
190+
scalar-only arrays, resulting in lower memory usage and better performance.
191+
192+
For one-off cloning, use the static ``deepClone()`` method::
193+
194+
use Symfony\Component\VarExporter\DeepCloner;
195+
196+
$clone = DeepCloner::deepClone($originalObject);
197+
198+
When you need to clone the same structure multiple times, create an instance
199+
to amortize the cost of graph analysis::
200+
201+
use Symfony\Component\VarExporter\DeepCloner;
202+
203+
$cloner = new DeepCloner($prototype);
204+
205+
$clone1 = $cloner->clone();
206+
$clone2 = $cloner->clone();
207+
208+
The ``isStaticValue()`` method returns ``true`` when the value does not need
209+
cloning (scalars, ``null``, enums, scalar-only arrays)::
210+
211+
$cloner = new DeepCloner($value);
212+
213+
if ($cloner->isStaticValue()) {
214+
// $value contains no objects or references, cloning is a no-op
215+
}
216+
217+
Use the ``cloneAs()`` method to deep-clone the root object using a different
218+
class (the target class must be compatible with the original, typically in the
219+
same hierarchy)::
220+
221+
$cloner = new DeepCloner($originalDog);
222+
$puppy = $cloner->cloneAs(Puppy::class);
223+
224+
``DeepCloner`` instances are serializable. The serialized form uses a compact
225+
representation that deduplicates class and property names, typically producing a
226+
smaller payload than ``serialize($value)`` itself.
227+
180228
Creating Lazy Objects
181229
---------------------
182230

0 commit comments

Comments
 (0)