Last 5.3 release ever available: PHP 5.3.29 - 5.3 now EOL

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

up
-3
mike at eastghost dot com
6 months 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 ) {}
?

----------
NO

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';
modify($obj);
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"

----------

http://stackoverflow.com/questions/19847781/do-i-need-to-use-the-ampersand-in-php-5-5-x-and-above-anymore
To Top