Marty Wallace
Marty Wallace

Reputation: 35734

PHP, does assignment use double memory for a variable?

If I have a large object and assign another variable to that object, does php create two objects, or does it use a pointer internally?

for example:

<?php
$myObject = new Class_That_Will_Consume_Lots_Of_Memory();
$testObject = $myObject;

In this example will i be using 2 x the memory footprint of a Class_That_Will_Consume_Lots_Of_Memory instance or will it be 1 of those and a pointer?

Upvotes: 2

Views: 177

Answers (2)

oroshnivskyy
oroshnivskyy

Reputation: 1579

Objects in PHP5 are passed by reference, arrays and other types passing is based on Copy on Write technique:

$a = ['a'=>'b'];
$b = $a; // Here we used 1x memory
$b['x'] = 'y'; // Now it become 2x memory

You can use memory_get_usage() to debug memory usage.

Upvotes: 0

Denis de Bernardy
Denis de Bernardy

Reputation: 78433

The latter: one object and a pointer/reference (and in fact, here, two pointers/references, since the first is one as well).

To get a new object, use clone.

Related: Are PHP5 objects passed by reference?

Upvotes: 1

Related Questions