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 value, usually TRue.

By the Way

The print() and echo() functions are similar in functionality and can be used interchangably. Whichever one you use is a matter of taste.


The abs() function, for example, requires a signed numeric value and returns the absolute value of that number. Let's try it out in Listing 7.1.

Listing 7.1. Calling the Built-in abs() Function
 1: <?php 2: $num = -321; 3: $newnum = abs($num); 4: echo $newnum; 5: //prints "321" 6: ?> 

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 the abs() function, 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.



Sams Teach Yourself PHP MySQL and Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (4th Edition)
ISBN: 067232976X
EAN: 2147483647
Year: 2003
Pages: 333
Authors: Julie Meloni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net