Pass by Reference in PHP5

PHP5 has a Pass-by-reference notation: &$bar in line 3 as seen here in the parameter to a function bar(); Basically, this is just a point from the sub routine’s “$bar” back to the caller’s $foo. In this case, a change to the reference variable $bar is reflected in the main variable $foo.

“bar points to/references foo”
$bar => $foo;


1< ?
2 //pass by reference...
3 function bar(&$bar = NULL)
4 {
5 print "\tbar:" . $bar . "\n";
6 $bar = 'bar';
7 print "\tbar:" . $bar . "\n";
8 }
9
10 $foo = 'foo';
11 print "foo:" . $foo . "\n";
12 bar($foo);
13 print "foo:" . $foo . "\n";
14
15
16 ?>

Output:


foo:foo
bar:foo
bar:bar
foo:bar

Recommended reading: PHP 5 Objects, Patterns, and Practice

VN:F [1.8.4_1055]
Rating: 8.0/10 (1 vote cast)
VN:F [1.8.4_1055]
Rating: 0 (from 0 votes)
Pass by Reference in PHP58.0101

2 Responses to “Pass by Reference in PHP5”

  1. reader says:

    I’d like to pass by value…

    UN:F [1.8.4_1055]
    Rating: 0.0/5 (0 votes cast)
    UN:F [1.8.4_1055]
    Rating: 0 (from 0 votes)
  2. Ian says:

    Just leave out the ampersand to pass by value, eg.

    function bar($bar = NULL)

    UN:F [1.8.4_1055]
    Rating: 0.0/5 (0 votes cast)
    UN:F [1.8.4_1055]
    Rating: 0 (from 0 votes)

Leave a Reply