Page 202 - Beginning PHP 5.3
P. 202
Part II: Learning the Language
You looked in some detail at how to call a function — whether built - in or user - defined — and explored
how the PHP engine behaves when a function is called. You also learned about variable functions — a
feature of PHP that lets you select which function to call while your script is running.
The main part of the chapter concentrated on writing your own functions. You studied:
❑ How to define a function
❑ How to specify function parameters, including optional parameters with default values
❑ The return statement that lets you return a value from a function, or exit a function
prematurely
❑ The difference between local, global, and static variables, and how to work with all three types
❑ The concept of anonymous functions, and how to create them
Next, you learned about references, and you saw how references allow functions to access and modify
variables outside of them.
Finally, you were introduced to the concept of recursion, where a function repeatedly calls itself until an
end condition is reached. By way of example, you used a recursive function to generate numbers in the
Fibonacci sequence.
Now that you know how to create and use functions, you ’ ll find it much easier to write larger PHP
scripts that are also easier to read and maintain. Try the following two exercises to brush up on your
function skills. You can find the solutions to these exercises in Appendix A.
The next chapter introduces object - oriented programming, which extends the idea of reusable code even
further and can add a lot of power and flexibility to your PHP applications.
Exercises
1. Write a function that takes an array argument, and returns a string containing XHTML markup for
a definition list where each key of the array is a term, and each corresponding value is a definition.
(Hint: An XHTML definition list element consists of < dl > ... < /dl > tags. Inside these tags,
terms are marked up using < dt > ... < /dt > tags, and definitions using < dd > ... < /dd > tags.)
2. A factorial of any given integer, n , is the product of all positive integers between 1 and n inclu-
sive. So the factorial of 4 is 1 × 2 × 3 × 4 = 24, and the factorial of 5 is 1 × 2 × 3 × 4 × 5 = 120. This
can be expressed recursively as follows:
❑ If n == 0, return 1. (This is the base case)
❑ If n > 0, compute the factorial of n – 1, multiply it by n , and return the result
Write a PHP script that uses a recursive function to display the factorials of the integers 0 to 10.
164
9/21/09 9:00:59 AM
c07.indd 164 9/21/09 9:00:59 AM
c07.indd 164