-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path05-circular-reference.php
More file actions
46 lines (40 loc) · 1.11 KB
/
05-circular-reference.php
File metadata and controls
46 lines (40 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
include './utils.php';
getMemoryUsage();
familyTree();
getMemoryUsage();
// Example 1: Circular reference keeps memory even out of scope.
// Allocated memory won't be free until end of script or until
class Person {
public $child;
public $parent;
public $data;
public function __construct() {
$this->data = range(1, 10000);
}
}
function familyTree() {
$jim = new Person();
$gwen = new Person();
$jim->child = $gwen;
$gwen->parent = $jim;
getMemoryUsage();
}
// Fix 1: Create a dereferencing method (not the same thing as __destruct)
// class Person {
// public $child;
// public $parent;
// public $data;
// public function __construct() {
// $this->data = range(1, 10000);
// }
// function removeRefs() {
// $this->child = NULL;
// $this->parent = NULL;
// }
// }
// Fix 2: Create a dereferencing method
// Some language use a programming construct of 'weak references' where the
// child reference does not protect the referenced object from garbage
// collection; but this feature doesn't exist in PHP although some have contrib:
// https://github.com/colder/php-weakref