tags:

views:

231

answers:

3

Hi,

iam studying for the Zend PHP5 Cerfitication, everything looks good but i cant find real world exampled for passing or returning variables my reference.

It would be very nice, if someone has an example when to use this?

Thanks in advance.

+1  A: 

Let's say you want to write a function that removes certain values from an array.

function remove_elements($array, $item1, $item2, ...) {
  ...
}

You could copy the array and return it. But what if you want to know if anything was removed? Instead you modify the array in-place and return the number of elements removed. So:

function remove_elements(&$array) {
  // remove elements
  return $number_removed;
}

If you create a complex structure inside your function you may want to return a reference to it rather than a copy of it. But this is a fairly marginal case because PHP uses copy-on-write (ie its not copied until it's modified) but there are some valid use cases.

Returning by reference makes more sense when you're writing a member function of a class. You could return a reference to a data member but this can also break encapsulation.

Lastly, it's worth noting that all objects are passed and returned by reference by default. Everything else is passed and returned by value.

cletus
Good answer for half the question, though this doesn't give info regarding returning by reference.
Mez
Mez
+1  A: 

Pass by reference: functions like asort()

$array = array(3, 2, 1);
asort($array);
Greg
+1  A: 

Objects in php5 are passed by reference by default.
Passing arguments by reference has already been answered...

As a (real world) example for a return value by reference pick any fluent interface where a method returns a reference to the same object as its own call-context ($this). This wouldn't work (as expected) if the return value was a copy/clone.

E.g.

class MyClass {  
  protected $foo = 'n/a';
  protected $bar = 'n/a';

  function foo($val) {
    $this->foo = (int)$val;
    return $this;
  }

  function bar($val) {
    $this->bar = (int)$val;
    return $this;
  }

  function __toString() {
    return 'foo='.$this->foo.' bar='.$this->bar;
  }
}

$o = new MyClass;
$o->foo(1)
  ->bar(2);
echo $o;

This prints foo=1 bar=2 and I think that's the result one would expect, no surprises here. If the method returned $this by value, it wouldn't work anymore. You can test that by forcing php to return a copy. Instead of the return $this lines use

return clone $this;

and the output will be

foo=1 bar=n/a

(and I wouldn't call that interface intuitive ;-))

VolkerK