8.3 Returning Values from a Function


You want to return a variable or an array or a Boolean value from a function.

Technique

Use the return statement to return values from a function, like so:

 <?php function need_full_report() {      // For this example, we'll just check if it's the end of the week     return (date("w") == 6); /* return true if it's Saturday */ } if (need_full_report ()) {     send_full_report(); } else {     send_current_report(); } ?> 

Comments

The return statement allows you to return only one value. (To return more than one value, see recipe 8.6.) This value can be of any PHP-supported type. In the example, we use the return value of the function to determine what kind of report to send.

PHP 4 supports returning values by reference. This is helpful when you want to return a large array or an object that was created in the function. The declaration of a function that returns a value by reference looks like this:

 <?php function &get_product_list($department) {     $product_list = array();     // Do database query and return the list of products which may be large     // ....     return $product_list; } $products = &get_product_list('rd'); ?> 

The result will be that instead of making a copy of $product_list and passing it back, the function will return a reference to $product_list , saving memory and execution time.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net