Calling a Function

Functions in a PHP program can be built-in (or, by being in an extension, effectively built-in) or user-defined. Regardless of their source, all functions are evaluated in the same way:

$someValue = function_name( [ parameter, ... ] );

The number of parameters a function requires differs from function to function (and, as we’ll see later, may even vary for the same function). The parameters supplied to the function may be any valid expression and must be in the specific order expected by the function. If the parameters are given out of order, the function may still run by a fluke, but it’s basically a case of garbage in = garbage out. A function’s documentation will tell you what parameters the function expects and what values you can expect to be returned.

Here are some examples of functions:

// strlen() is a built-in function that returns the length of a string
$length = strlen("PHP"); // $length is now 3
// sin() and asin() are the sine and arcsine math functions
$result = sin(asin(1)); // $result is the sine of arcsin(1), or 1.0

// unlink() deletes a file
$result = unlink("functions.txt"); // false if unsuccessful

In the first example, we give an argument, "PHP", to the function strlen(), which gives us the number of characters in the string it’s given. In this case, it returns 3, which is assigned to the variable $length. This is the simplest and most common way to use a function.

The second example passes the result of asin(1) to the sin() function. Since the ...

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.