inside the function, $var = contents outside the function, $var = contents Note that the variable is in scope from the point in which the line global $var;is executed.We could have decla
Trang 1inside the function, $var = contents outside the function, $var = contents
Note that the variable is in scope from the point in which the line global $var;is executed.We could have declared the function above or below where we call it (Note that function scope is quite different from variable scope!) The location of the function declaration is inconsequential, what is important is where we call the function and there-fore execute the code within it
You can also use the globalkeyword at the top of a script when a variable is first used to declare that it should be in scope throughout the script.This is possibly a more common use of the globalkeyword
You can see from the preceding examples that it is perfectly legal to reuse a variable name for a variable inside and outside a function without interference between the two
It is generally a bad idea however because without carefully reading the code and think-ing about scope, people might assume that the variables are one and the same
Pass by Reference Versus Pass by Value
If we want to write a function called increment()that allows us to increment a value,
we might be tempted to try writing it as follows:
function increment($value, $amount = 1) {
$value = $value +$amount;
}
This code will be of no use.The output from the following test code will be "10"
$value = 10;
increment ($value);
echo $value;
The contents of $valuehave not changed
This is because of the scope rules.This code creates a variable called $valuewhich contains 10 It then calls the function increment().The variable $valuein the function
is created when the function is called One is added to it, so the value of $valueis 11 inside the function, until the function ends, and we return to the code that called it In this code, the variable $valueis a different variable, with global scope, and therefore unchanged
One way of overcoming this is to declare $valuein the function as global, but this means that in order to use this function, the variable that we wanted to increment would need to be named $value A better approach would be to use pass by reference.
The normal way that function parameters are called is called pass by value.When you
pass a parameter, a new variable is created which contains the value passed in It is a copy
of the original.You are free to modify this value in any way, but the value of the original variable outside the function remains unchanged
Trang 2138 Chapter 5 Reusing Code and Writing Functions
The better approach is to use pass by reference Here, when a parameter is passed to a
function, rather than creating a new variable, the function receives a reference to the original variable.This reference has a variable name, beginning with a dollar sign, and can be used in exactly the same way as another variable.The difference is that rather than having a value of its own, it merely refers to the original Any modifications made
to the reference also affect the original
We specify that a parameter is to use pass by reference by placing an ampersand (&) before the parameter name in the function’s definition No change is required in the function call
The preceding increment()example can be modified to have one parameter passed
by reference, and it will work correctly
function increment(&$value, $amount = 1) {
$value = $value +$amount;
}
We now have a working function, and are free to name the variable we want to incre-ment anything we like As already incre-mentioned, it is confusing to humans to use the same name inside and outside a function, so we will give the variable in the main script a new name.The following test code will now echo 10 before the call to increment(), and 11 afterwards
$a = 10;
echo $a.'<br />';
increment ($a);
echo $a.'<br />';
Returning from Functions
The keyword returnstops the execution of a function.When a function ends because either all statements have been executed or the keyword return is used, execution returns
to the statement after the function call
If you call the following function, only the first echo statement will be executed function test_return()
{ echo 'This statement will be executed';
return;
echo 'This statement will never be executed';
}
Obviously, this is not a very useful way to use return Normally, you will only want to return from the middle of a function in response to a condition being met
Trang 3An error condition is a common reason to use a returnstatement to stop execution
of a function before the end If, for instance, you wrote a function to find out which of two numbers was greater, you might want to exit if any of the numbers were missing
function larger( $x, $y ) {
if (!isset($x)||!isset($y)) {
echo 'This function requires two numbers';
return;
}
if ($x>=$y) echo $x;
else echo $y;
echo '<br />';
}
The built-in function isset()tells you whether a variable has been created and given a value In this code, we are going to give an error message and return if either of the parameters has not been set with a value.We test this by using !isset(), meaning
“NOT isset(),” so the if statement can be read as “if x is not set or if y is not set”.The function will return if either of these conditions is true
If the returnstatement is executed, the subsequent lines of code in the function will
be ignored Program execution will return to the point at which the function was called
If both parameters are set, the function will echo the larger of the two
The output from the following code:
$a = 1;
$b = 2.5;
$c = 1.9;
larger($a, $b);
larger($c, $a);
larger($d, $a);
will be as follows:
2.5 1.9 This function requires two numbers
Returning Values from Functions
Exiting from a function is not the only reason to use return Many functions use returnstatements to communicate with the code that called them Rather than echoing the result of the comparison in our larger()function, our function might have been
Trang 4140 Chapter 5 Reusing Code and Writing Functions
more useful if we returned the answer.This way, the code that called the function can choose if and how to display or use it.The equivalent built-in function max()behaves in this way
We can write our larger()function as follows:
function larger ($x, $y) {
if (!isset($x)||!isset($y)) return false;
else if ($x>=$y) return $x;
else return $y;
}
Here we are returning the larger of the two values passed in.We will return an obviously different value in the case of an error If one of the numbers is missing, we will return false.The only caveat with this approach is that programmers calling the function must test the return type with ===to make sure that falseis not confused with 0
For comparison, the built-in function max()returns nothing if both variables are not set, and if only one was set, returns that one
The following code:
$a = 1; $b = 2.5; $c = 1.9;
echo larger($a, $b)."<br />";
echo larger($c, $a)."<br />";
echo larger($d, $a)."<br />";
will produce this output because $d does not exist and false is not visible:
2.5 1.9
Functions that perform some task, but do not need to return a value, often return true
or falseto indicate if they succeeded or failed.The boolean values trueand falsecan
be represented with integer values 1 and 0 respectively, although they are of different types
Code Blocks
We declare that a group of statements are a block by placing them within curly braces This does not affect most of the operation of your code, but has specific implications including the way control structures such as loops and conditionals execute
The following two examples work very differently:
Trang 5Example Without Code Block
for($i = 0; $i < 3; $i++ ) echo 'Line 1<br />';
echo 'Line 2<br />';
Example with Code Block
for($i = 0; $i < 3; $i++ ) {
echo 'Line 1<br />';
echo 'Line 2<br />';
}
In both examples, the forloop is iterated through three times In the first example, only the single line directly below this is executed by the forloop.The output from this example is as follows:
Line 1 Line 1 Line 1 Line 2
The second example uses a code block to group two lines together.This means that both lines are executed three times by the forloop.The output from this example is as fol-lows:
Line 1 Line 2 Line 1 Line 2 Line 1 Line 2
Because the code in these examples is properly indented, you can probably see the dif-ference between them at a glance.The indenting of the code is intended to give readers
a visual interpretation of what lines are affected by the forloop However, note that spaces do not affect how PHP processes the code
In some languages, code blocks affect variable scope.This is not the case in PHP
Recursion
Recursive functions are supported in PHP A recursive function is one that calls itself.These
functions are particularly useful for navigating dynamic data structures such as linked lists and trees
However, few Web-based applications require a data structure of this complexity, and
so we have minimal use for recursion Recursion can be used instead of iteration in many cases because both of these allow you to do something repetitively Recursive