Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

6.3. Passing Values by Reference

Problem

You want to pass a variable to a function and have it retain any changes made to its value inside the function.

Solution

To instruct a function to accept an argument passed by reference instead of value, prepend an & to the parameter name in the function prototype:

function wrap_html_tag(&$string, $tag = 'b') {
    $string = "<$tag>$string</$tag>";
}

Now there’s no need to return the string because the original is modified in-place.

Discussion

Passing a variable to a function by reference allows you to avoid the work of returning the variable and assigning the return value to the original variable. It is also useful when you want a function to return a boolean success value of true or false, but you still want to modify argument values with the function.

You can’t switch between passing a parameter by value or reference; it’s either one or the other. In other words, there’s no way to tell PHP to optionally treat the variable as a reference or as a value.

Actually, that statement isn’t 100% true. If the configuration directive allow_call_time_pass_reference is enabled, PHP lets you optionally pass a value by reference by prepending an ampersand to the variable’s name. However, this feature has been deprecated since PHP 4.0 Beta 4, and PHP issues explicit warnings that this feature may go away in the future when you employ call-time pass-by-reference. Caveat coder.

Also, if a parameter is declared to accept a value by reference, you can’t pass ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata