Recipe 6.1. Accessing Function Parameters

6.1.1. Problem

You want to access the values passed to a function.

6.1.2. Solution

Use the names from the function prototype:

function commercial_sponsorship($letter, $number) {     print "This episode of Sesame Street is brought to you by ";     print "the letter $letter and number $number.\n"; } commercial_sponsorship('G', 3); commercial_sponsorship($another_letter, $another_number);

6.1.3. Discussion

Inside the function, it doesn't matter whether the values are passed in as strings, numbers, arrays, or another kind of variable. You can treat them all the same and refer to them using the names from the prototype.

Unless specified, all non-object values being passed into and out of a function are passed by value, not by reference. (By default, objects are passed by reference.) This means PHP makes a copy of the value and provides you with that copy to access and manipulate. Therefore, any changes you make to your copy don't alter the original value. Here's an example:

function add_one($number) {     $number++; } $number = 1; add_one($number); print "$number\n"; 1

If the variable was passed by reference, the value of $number would be 2.

In many languages, passing variables by reference has the additional benefit of being significantly faster than passing them by value. While the passing-by-reference is faster in PHP, the speed difference is marginal. For that reason, we suggest passing variables by reference only when actually necessary and never as a performance-enhancing trick.

6.1.4. See Also

Recipe 6.3 to pass values by reference and Recipe 6.6 to return values by reference.

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: