Calling Functions
Functions come in two flavorsthose built in to the language and those you define yourself. PHP has hundreds of built-in functions. Take a look at the following snippet for an example of a function use:
print ("Hello Web!");
In this example, we call the print() function, passing it the string "Hello Web!". The function then goes about the business of writing the string. A function call consists of the function name (print 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, separated by commas:
some_function ($an_argument , $another_argument );
print() is typical for a function in that it returns a value. Most functions give you some information back when they've completed their taskthey usually at least tell whether their mission was successful. print() returns a Boolean.
![]() | The print() and echo() functions are similar in functionality and are used interchangably throughout this book. Whichever one you use is a matter of taste. |
Listing 6.1 Calling the Built-in abs() Function
1: <html>
2: <head>
3: <title>Listing 6.1</title>
4: </head>
5: <body>
6: <?php
7: $num = -321;
8: $newnum = abs( $num );
9: echo $newnum;
10: //prints "321"
11: ?>
12: </body>
13: </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 display the result.Put these lines into a text file called abs.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:
321
In fact, we could have dispensed with temporary variables altogether, passing our number straight to abs(), and directly printing the result:
echo abs(-321);
We used the temporary variables $num and $newnum, though, to make each step of the process as clear as possible. Sometimes you can make your code more readable by breaking it up into a greater number of simple expressions.You can call user-defined functions in exactly the same way that we have been calling built-in functions.