Section 2.8. Functions

2.8. Functions

A function in PHP can be built-in or user-defined; however, they are both called the same way.

The general form of a function call is

func(arg1,arg2,...)

The number of arguments varies from one function to another. Each argument can be any valid expression, including other function calls.

Here is a simple example of a predefined function:

$length = strlen("John");

strlen is a standard PHP function that returns the length of a string. Therefore, $length is assigned the length of the string "John": four.

Here's an example of a function call being used as a function argument:

$length = strlen(strlen("John"));

You probably already guessed the result of this example. First, the inner strlen("John") is executed, which results in the integer 4. So, the code simplifies to

$length = strlen(4);

strlen() expects a string, and therefore (due to PHP's magical auto-conversion between types) converts the integer 4 to the string "4", and thus, the resulting value of $length is 1, the length of "4".

2.8.1. User-Defined Functions

The general way of defining a function is

function function_name (arg1, arg2, arg3, ...) { statement list }

To return a value from a function, you need to make a call to return expr inside your function. This stops execution of the function and returns expr as the function's value.

The following example function accepts one argument, $x, and returns its square:

function square ($x) { return $x*$x; }

After defining this function, it can be used as an expression wherever you desire.

For example:

print 'The square of 5 is ' . square(5);

2.8.2. Function Scope

Every function has its own set of variables. Any variables used outside the function's definition are not accessible from within the function by default. When a function starts, its function parameters are defined. When you use new variables inside a function, they are defined within the function only and don't hang around after the function call ends. In the following example, the variable $var is not changed by the function call:

function func () { $var = 2; } $var = 1; func(); print $var;

When the function func is called, the variable $var, which is assigned 2, is only in the scope of the function and thus does not change $var outside the function. The code snippet prints out 1.

Now what if you actually do want to access and/or change $var on the outside? As mentioned in the "Variables" section, you can use the built-in $GLOBALS[] array to access variables in the global scope of the script.

A global keyword also enables you to declare what global variables you want to access, causing them to be imported into the function's scope. However, using this keyword is not recommended for various reasons, such as misbehaving with assigning values by reference, not supporting unset(), and so on.

Here's a short description of itbut please, don't use it!

The syntax is

global $var1, $var2, ...;

Adding a global line for the previous example results in the following:

2.8.3. Returning Values By Value

You can tell from the previous example that the return statement is used to return values from functions. The return statement returns values by value, which means that a copy of the value is created and is returned to the caller of the function. For example:

This code prints the number 10. However, making changes to $value before the print statement only affects $value and not the global variable $num. This is because its value was returned by the get_global_variable_value() by value and not by reference.

2.8.4. Returning Values By Reference

PHP also allows you to return variables by reference. This means that you're not returning a copy to the variable, but you're returning the address of your variable instead, which enables you to change it from the calling scope. To return a variable by-reference, you need to define the function as such by placing an & sign in front of the function's name and in the caller's code, assigning the return value by reference to $value:

You can see that $num was successfully modified by modifying $value, because it is a reference to the global variable $num.

You won't need to use this returning method often. When you do, use it with care, because forgetting to assign by reference the by-reference returned value can lead to bugs that are difficult to track down.

2.8.5. Declaring Function Parameters

As previously mentioned, you can pass an arbitrary amount of arguments to a function. There are two different ways of passing these arguments. The first is the most common, which is called passing by value, and the second is called passing by reference. Which kind of argument passing you would like is specified in the function definition itself and not during the function call.

2.8.5.1 By-Value Parameters

Here, the argument can be any valid expression, the expression is evaluated, and its value is assigned to the corresponding variable in the function. For example, here, $x is assigned the value 8 and $y is assigned the value of $c:

function pow($x, $y) { ... } pow(2*4, $c);

2.8.5.2 By-Reference Parameters

Passing by-reference requires the argument to be a variable. Instead of the variable's value being passed, the corresponding variable in the function directly refers to the passed variable whenever used. Thus, if you change it inside the function, it affects the sent variable in the outer scope as well:

The & sign that proceeds $n in the function parameters tells PHP to pass it by-reference, and the result of the function call is $number squared; thus, this code would print 16.

2.8.5.3 Default Parameters

Default parameters like C++ are supported by PHP. Default parameters enable you to specify a default value for function parameters that aren't passed to the function during the function call. The default values you specify must be a constant value, such as a scalar, array with scalar values, or constant.

This code results in $num being incremented to 8. First, it is incremented by 1 by the first call to increment, where the default increment size of 1 is used, and second, it is incremented by 3, altogether by 4.

Note

When you a call a function with default arguments, after you omit a default function argument, you must emit any following arguments. This also means that following a default argument in the function's definition, all other arguments must also be declared as default arguments.

2.8.6. Static Variables

Like C, PHP supports declaring local function variables as static. These kind of variables remain in tact in between function calls, but are still only accessible from within the function they are declared. Static variables can be initialized, and this initialization only takes place the first time the static declaration is reached.

Here's an example for the use of static that runs initialization code the first time (and only the first time) the function is run:

function do_something() { static first_time = true; if (first_time) { // Execute this code only the first time the function is called ... } // Execute the function's main logic every time the function is called ... }