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

(singke) #1

Chapter 4. FUNCTIONS


Declaring a Function.........................................................................................


The return Statement.....................................................................................


Scope and the global Statement...............................................................


Arguments


Recursion...............................................................................................................


Dynamic Function Calls


You probably have noticed the use of several functions in the preceding chapters. Date
and print are built-in functions that are always available for you. PHP also allows you to
declare your own functions.


Functions expand the idea of repeating a block of code. They allow you to execute a
block of code arbitrarily throughout your script. You declare a block of code as a function
and then you are able to call the function anywhere. When calling a function, you pass
any number of arguments, and the function, returns a value.


Declaring a Function


When you declare a function, you start with the function statement. Next comes a name
for your function. Inside the parentheses is a list of arguments separated by commas. You
may choose to have no arguments. Figure 4-1 shows you the form of a function
declaration.


Figure 4-1. Declaring a function.

In other languages, including older versions of PHP, you must declare a function above
any call to it. This is not true of PHP 4. You may put a function declaration after calls
made to it. When you call a function, you write its name followed by parentheses, even if
there are no arguments to pass.


Functions allow you to put together a block of code that you will repeat several times
throughout your script. Your motivation may be to avoid typing identical code in two or
more places, or it could be to make your code easier to understand. Consider Listing 4.1.
It declares a function called printBold that prints any text with bold tags around it.

Free download pdf