Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

If you follow return with an expression, the value of the expression will be passed back.
Listing 4.2 demonstrates this idea by taking a string and returning it wrapped in bold
tags.


Listing 4.2 A Simple Function Using return


<?
function makeBold($inputText)
{
$boldedText = "";
$boldedText .= $inputText;
$boldedText .= "
";


return($boldedText);
}


print("This Line is not Bold
\n);
print(makeBold("This Line is Bold"). "
\n");
print("This Line is not Bold
\n");
?>


Scope and the global Statement


As discussed in Chapter 2, variables inside a function exist inside a name space separate
from the global name space. Variables inside a function are private property and may
never be seen or manipulated outside the function. However, there are two ways a
function may access variables in the global scope: the global statement and the GLOBALS
array.


The global statement brings a variable into a function's name space. Thereafter the
variable may be used as if it were outside the function. Any changes to the variable will
persist after execution of the function ceases. In the same way, it is possible to refer to
global variables through the array GLOBALS. The array is indexed by variable names, so if
you create a variable named userName you can manipulate it inside a function by writing
$GLOBALS["userName"].


Also noted in Chapter 2 is the idea of static variables. If a variable is declared to be
static, it retains its value between function calls. Listing 2.3 demonstrates the use of static
variables.


Arguments


When declaring a function, you may declare arguments inside the parentheses, each
separated by a comma. The arguments must be preceded by a dollar sign. They become
variables inside the function. When the function is called, it expects values to be passed
that will fill the arguments in the order declared.


Arguments, by default, copy the passed value into the local variable. If the variable is
preceded by the & operator, the variable instead becomes an alias for the passed variable.

Free download pdf