6.1. Accessing Function Parameters

Problem

You want to access the values passed to a function.

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);

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.

Unlike in C, you don’t need to (and, in fact, can’t) describe the type of variable being passed in. PHP keeps track of this for you.

Also, unless specified, all values being passed into and out of a function are passed by value, not 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 also has the additional benefit of being significantly faster than by value. While this is also true in PHP, the speed difference is marginal. For that reason, we suggest passing variables by reference only when actually ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.