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.

Rewrite the previous script the following way:

 function func () {     $GLOBALS["var"] = 2; } $var = 1; func(); print $var; 

It prints the value 2.

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:

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

This way of writing the example also prints the number 2.

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:

 function get_global_variable_value($name) {     return $GLOBALS[$name]; } $num = 10; $value = get_global_variable_value("num"); print $value; 

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:

 function &get_global_variable($name) {     return $GLOBALS[$name]; } $num = 10; $value =& get_global_variable("num"); print $value . "\n"; $value = 20; print $num; 

The previous code prints as
 10 20 

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:

 function square(&$n) {     $n = $n*$n; } $number = 4; square($number); print $number; 

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.

The following is an example for using default parameters:

 function increment(&$num, $increment = 1) {     $num += $increment; } $num = 4; increment($num); increment($num, 3); 

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



    PHP 5 Power Programming
    PHP 5 Power Programming
    ISBN: 013147149X
    EAN: 2147483647
    Year: 2003
    Pages: 240

    Similar book on Amazon

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