Page 180 - Beginning PHP 5.3
P. 180
Part II: Learning the Language
optionally return a value that can then be read by the calling code. In this way, the calling code can
communicate with the function.
You can think of a function as a black box. The code that calls a function doesn ’ t need to know what ’ s
inside the function; it just uses the function to get the job done.
Why Functions Are Useful
Functions are an important part of any programming language, and you ’ ll find yourself using and
creating functions in PHP all the time. Functions are useful for a number of reasons:
❑ They avoid duplicating code — Let ’ s say you ’ ve written some PHP code to check that an email
address is valid. If you ’ re writing a webmail system, chances are you ’ ll need to check email
addresses at lots of different points in your code. Without functions, you ’ d have to copy and
paste the same chunk of code again and again. However, if you wrap your validation code
inside a function, you can just call that function each time you need to check an email address
❑ They make it easier to eliminate errors — This is related to the previous point. If you ’ ve copied
and pasted the same block of code twenty times throughout your script, and you later find that
code contained an error, you ’ ll need to track down and fix all twenty errors. If your code was
inside a function, you ’ d only need to fix the bug in a single place
❑ Functions can be reused in other scripts — Because a function is cleanly separated from the rest
of the script, it ’ s easy to reuse the same function in other scripts and applications
❑ Functions help you break down a big project — Writing a big Web application can be
intimidating. By splitting your code into functions, you can break down a complex application
into a series of simpler parts that are relatively easy to build. (This also makes it easier to read
and maintain your code, as well as add more functionality later if needed)
Calling Functions
If you ’ ve worked through the previous chapters you ’ ve already called quite a few of PHP ’ s built - in
functions. To call a function, you write the function name, followed by an opening and a closing
parenthesis:
functionName()
If you need to pass arguments to the function, place them between the parentheses, separating each
argument by commas:
functionName( argument )
functionName( argument1, argument2 )
142
9/21/09 9:00:51 AM
c07.indd 142
c07.indd 142 9/21/09 9:00:51 AM