Bulgaria PHP Conference

What References Are

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on. See What References Are Not for more information. Instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.

add a note add a note

User Contributed Notes 1 note

mike at eastghost dot com
1 year ago
If I make a function, using PHP 5.5.5:
function recurring_mailer_form( $form, $form_state ) {}

Is it the same as:
function recurring_mailer_form( $form,  & $form_state ) {}


Using php 5.5.x+

If you pass an object as usual (ie, without the ampersand), you can (only) alter the object's state (properties) (but not change the whole obj into a new obj)

$obj is an instance of the class Test which contains a member variable called hello:

function modify($obj) { $obj->hello = 'world (modified)!'; }

$obj->hello = 'world';
var_dump($obj->hello);  // outputs "world (modified!)"


Now, using the same code but assigning another value to $obj instead modifying the object's state results in no modification:

function modify($obj) { $obj = 42; }
var_dump($obj->hello);  // outputs "world"


Only accepting the parameter explicitly as a reference gives us the ability to completely change the variable's contents:

function modify(&$obj) { $obj = 42; }
var_dump($obj);         // outputs "42"


To Top