reference stays reference even if passed by value

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Hello all,

I started porting a huge PHP application to PHP5 and encountered a
problem with references. I don't know whether the behavior I see is a
bug or a feature. The following nonsens test program should make clear
what's the problem:

  class test {
    public $_foo = null;

    public function __construct($foo) {
      $this->_foo = $foo;

  function fct1(&$p) {
    print "before call to fct2(): $p->_foo\n";
    print "after call to fct2(): $p->_foo\n";

  function fct2($p) {
    print "in fct2(): $p->_foo\n";
    $p->_foo = "bla bla bla";
    print "after modifying value parameter fct2(): $p->_foo\n";

  $t = new test("Hello World!");

If I evaluate this code with php v5.1.2 I get the following output:

  before call to fct2(): Hello World!
  in fct2(): Hello World!
  after modifying value parameter fct2(): bla bla bla
  after call to fct2(): bla bla bla

I don't understand this: fct1() takes a parameter as reference, so
fct1() should be able to change the argument I pass to it, but it does
not do this. Instead it call fct2(), a function that takes a "value
parameter". In my understanding, fct2() can change its argument, but
changes to not affect the caller, ie. changing the parameter should
not affect the variable passed to it in the callers scope.

Am I wrong or is this a (known) bug?

BTW: The PHP4 version works fine with php4.


Re: reference stays reference even if passed by value

On Mon, 09 Jul 2007 11:10:38 +0200,  

Quoted text here. Click to load it

It's a change in PHP5: objects are passed by reference by default instead  
of by value. If you need a copy you should use the clone keyword.

Rik Wasmus

Site Timeline