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. The very first script in this book, which appears in Hour 3, "Installing and Configuring PHP," consists of a single function call:

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. Arguments in such cases must be separated by commas:

some_function( $an_argument, $another_argument);

print() is typical in that it returns a value. Most functions give you some information back when they've completed their task?they usually at least tell whether their mission was successful. print() returns a Boolean.

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 6.1.

graphics/book.gif

print() is not a typical function in that it does not require parentheses in order to run successfully:

print("Hello Web!");

and

print "Hello Web!";

are equally valid. This is an exception. All other functions require parentheses, whether or not they accept arguments.


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: print $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 print 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:

print( 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.



    Part III: Getting Involved with the Code