PHP References

When To Use References

Articles > Webmaster > PHP References > When To Use References

If you use the PHP variable references feature you can have two different variables that refer to the same data. For example, imagine that you had an array of people, and a function that returned an array of just the men.

If you do not use references, the second array contains copies of the original records. This means that if you modify the records in the second array you have absolutely no effect on the records in the first array. Thus, in the example below, when we change the first man to a woman we only change the copy of Adam that resides in the $men array; the original Adam in the $people array is unaffected.

And, in addition, you are using more memory because every assignment statement creates a copy of the record. If you have a large number of records, or if your records are very large, you might use up a lot of memory by the time your script finishes executing.

If you use references when processing the array you can get a better result and save memory.

// a find function that creates
// a list of COPIES of matching
// person records

function findMen($list) {
    $results = array();
    foreach ($list as $p) {
        if ($p->gender == "male")
            $results[] = $p;
    }
    return $results;
}

// find the men, and change the
// first man into a woman

$men = findMen($people);
$men[0]->gender = "female";

people

Person

name: Adam

age: 37

gender: female

Person

name: Betty

age: 35

gender: female

Person

name: Charles

age: 25

gender: male

Person

name: Diane

age: 32

gender: female

Person

name: Eric

age: 38

gender: male

men

Person

name: Adam

age: 37

gender: female

Person

name: Charles

age: 25

gender: male

Person

name: Eric

age: 38

gender: male