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.

The old value of $black is lost. Instead, $black is now another name for the value<br />

that is stored in $white:<br />

$big_long_variable_name = "<strong>PHP</strong>";<br />

$short =& $big_long_variable_name;<br />

$big_long_variable_name .= " rocks!";<br />

print "\$short is $short\n";<br />

print "Long is $big_long_variable_name\n";<br />

$short is <strong>PHP</strong> rocks!<br />

Long is <strong>PHP</strong> rocks!<br />

$short = "<strong>Programming</strong> $short";<br />

print "\$short is $short\n";<br />

print "Long is $big_long_variable_name\n";<br />

$short is <strong>Programming</strong> <strong>PHP</strong> rocks!<br />

Long is <strong>Programming</strong> <strong>PHP</strong> rocks!<br />

After the assignment, the two variables are alternate names for the same value.<br />

Unsetting a variable that is aliased does not affect other names for that variable’s<br />

value, though:<br />

$white = "snow";<br />

$black =& $white;<br />

unset($white);<br />

print $black;<br />

snow<br />

Functions can return values by reference (for example, to avoid copying large strings<br />

or arrays, as discussed in Chapter 3):<br />

function &ret_ref() { // note the &<br />

$var = "<strong>PHP</strong>";<br />

return $var;<br />

}<br />

$v =& ret_ref(); // note the &<br />

Variable Scope<br />

The scope of a variable, which is controlled by the location of the variable’s declaration,<br />

determines those parts of the program that can access it. There are four types of<br />

variable scope in <strong>PHP</strong>: local, global, static, and function parameters.<br />

Local scope<br />

A variable declared in a function is local to that function. That is, it is visible only to<br />

code in that function (including nested function definitions); it is not accessible outside<br />

the function. In addition, by default, variables defined outside a function (called<br />

global variables) are not accessible inside the function. For example, here’s a function<br />

that updates a local variable instead of a global variable:<br />

function update_counter ( ) {<br />

$counter++;<br />

}<br />

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

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

Variables | 31

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

Saved successfully!

Ooh no, something went wrong!