[ Team LiB ] Previous Section Next Section

Calling Functions

Functions come in two flavors—those built in to the language and those you define yourself. PHP has hundreds of built-in functions. One of the earliest scripts in this book used the gettype() function:


gettype( $testing );

We called gettype() and passed it the $testing variable. The function then went about the business of testing the variable. A function call consists of the function name—gettype in this case—followed by parentheses. If you want to pass information to the function, you place it between these parentheses. A piece of information passed to a function in this way is called an argument. Some functions require that more than one argument be passed to them. Arguments in these cases must be separated by commas, like so:


some_function( $an_argument, $another_argument );

gettype() is typical in that it returns a value. Most functions give you some information back when they've completed their task, if only to tell you whether their mission was successful. gettype() reports on its testing by returning a string that contains the type of the argument it was passed.

abs() is another example of a built-in function. It requires a signed numeric value and returns the absolute value of that number. Let's try it in Listing 6.1.

Listing 6.1 Calling the Built-in abs() Function
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 6.1 Calling the Built-in abs() function</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $num = -321;
12: $newnum = abs( $num );
13: print $newnum;
14: // prints "321"
15: ?>
16: </div>
17: </body>
18: </html>

In this example, we assign the value -321 to a variable $num. We then pass that variable to the abs() function, which makes the necessary calculation and returns a new value. We assign this to the variable $newnum and print the result. In fact, we could have dispensed with temporary variables altogether, passing our number straight to abs(), and directly printing the result:


print( abs( -321 ) );

We used the temporary variables $num and $newnum, though, to make each step of the process as clear as possible. Sometimes your code can be made more readable by breaking it up into a greater number of simple expressions.

You can call user-defined functions in exactly the same way we have been calling built-in functions.

    [ Team LiB ] Previous Section Next Section