2

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?

Marty Wallace
  • 34,046
  • 53
  • 137
  • 200

2 Answers2

1

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?

Community
  • 1
  • 1
Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154
0

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.

oroshnivskyy
  • 1,559
  • 1
  • 10
  • 5