05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Missing Parameters<br />

<strong>PHP</strong> lets you be as lazy as you want—when you call a function, you can pass any<br />

number of arguments to the function. Any parameters the function expects that are<br />

not passed to it remain unset, and a warning is issued for each of them:<br />

function takes_two( $a, $b ) {<br />

if (isset($a)) { echo " a is set\n"; }<br />

if (isset($b)) { echo " b is set\n"; }<br />

}<br />

echo "With two arguments:\n";<br />

takes_two(1, 2);<br />

echo "With one argument:\n";<br />

takes_two(1);<br />

With two arguments:<br />

a is set<br />

b is set<br />

With one argument:<br />

Warning: Missing argument 2 for takes_two( )<br />

in /path/to/script.php on line 6<br />

a is set<br />

Return Values<br />

<strong>PHP</strong> functions can return only a single value with the return keyword:<br />

function return_one() {<br />

return 42;<br />

}<br />

To return multiple values, return an array:<br />

function return_two ( ) {<br />

return array("Fred", 35);<br />

}<br />

By default, values are copied out of the function. A function declared with an &<br />

before its name returns a reference (alias) to its return value:<br />

$names = array("Fred", "Barney", "Wilma", "Betty");<br />

function & find_one($n) {<br />

return $names[$n];<br />

}<br />

$person =& find_one(1); // Barney<br />

$person = "Barnetta"; // changes $names[1]<br />

In this code, the find_one( ) function returns an alias for $names[1], instead of a copy<br />

of its value. Because we assign by reference, $person is an alias for $names[1], and the<br />

second assignment changes the value in $names[1].<br />

This technique is sometimes used to return large string or array values efficiently<br />

from a function. However, <strong>PHP</strong>’s copy-on-write/shallow-copy mechanism usually<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Return Values | 69

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!