April 8, 2010

Functions and Constructs in PHP


In PHP a function is a predefined set of commands that are carried out when the function is invoked. In addition to being able to write your own functions, PHP has a number of predefine functions for you to use. In function, the interpreter simply starts at the beginning and works its way to the end in a linear fashion. In the real world, this simple approach is rarely practical; for example, you might want to perform a certain operation more than once in different portions of your code. To do so, PHP supports a facility known as a function.

Functions must be declared using the following syntax:
function function_name ([param1], [param 2])
In PHP each function is assigned a name and can receive one or more than one parameters. The parameters exist as variables throughout the execution of the entire function.
Simple function with a parameter:

<?php
function square ($sqr)
{
return $sqr * $sqr;
}
$my_sqr = 50;
echo square ($my_sqr);
?>

The $sqr variable is created whenever the square function is called and initialized with the value passed to it. The return statement is used to return a value from the
function, which later on passes to the calling script. Normally, parameters are passed by some value, this means that, in the previous example, a copy of the $my_sqr variable is placed in the $sqr variable when the function begins, and any changes to the newly generated variable in the function body does not affects former value. But you can overcome this situation by passing a parameter by reference so that any changes performed within the function will also be reflected to the former value. In passing the reference it not only passes the value but also the reference for that value.

<?php
function square (&$my_sqr)
{
$my_sqr += 10;
return $my_sqr * $my_sqr;
}
$sqr = 50;
echo square ($sqr);
?>

You can also assign a default value to any of the parameters of a function when declaring it. This way, if the caller does not provide a value for the parameter, the default one will be used instead:

<?php
function square ($my_sqr = 50)
{
return $my_sqr * $my_sqr;
}
echo square ();
?>

In this case, because no value has been passed for $sqr, the default of 50 will be used by the interpreter. Note that you can’t assign a default value to a parameter passed by reference.

Scope of Functions and Variable
It’s significant to point out that there is no connection between the name of a variable declared inside a function body and any equivalent variables declared outside of it. In PHP, variable scope works differently from most other languages so that what resides in the global scope is not automatically available in a function’s scope. It can be stated more clearly from the following example:

<?php
function square ()
{
$sqr += 10;
return $sqr * $sqr;
}
$sqr = 50;
echo square ();
?>

In this case, the script assumes that the $sqr variable, which is part of the global scope, will be automatically included in the scope of square(). However, this does not take place, so $sqr has a value of Null inside the function, resulting in a return value of 0. If you want to import global variables inside a function’s scope, you can do so by using the global statement:

<?php
function square ()
{
global $sqr;
$sqr += 10;
return $sqr * $sqr;
}
$years = 50;
echo square ();
?>

The $sqr variable is now accessible to the function, where it can be used and modified. Note that by importing the variable inside the function’s scope, any changes made to it will be reflected in the global scope as well—in other words, you’ll be accessing the variable itself, and not an ad hoc copy as you would with a parameter passed by value.

Functions with Variable Parameters
You can also know about the number and types of parameter passed to a particular function. For this you have to just create a function that accepts a variable number of arguments using a number of functions that PHP makes available for you:

func_num_args() returns the number of parameters passed to a function.
func_get_arg($arg_num) returns a particular parameter, given its position in the parameter list.
func_get_args() returns an array containing all the parameters in the parameter list.

As an example, let’s write a function that calculates the arithmetic average of all the parameters passed to it:

<?php
function class_avg()
{
$arg =  func_num_args();
if ($arg == 0)
return 0;
$total = 0;
for ($i = 0; $i < $arg; $i++)
$total += func_get_args($i);
return $total / $arg;
}
echo class_avg (89, 44, 64, 49, 75, 90);
?>

In the preceding example, we started the script by determining the number of arguments and if there is no argument then we are exiting immediately from the function. The reason behind this is that the last instruction would cause a division-by-zero error. Further, we create a for loop that simply cycles through each parameter in sequence, adding its value to the sum. At last, we calculate and return the average value by dividing the sum by the number of parameters. Note how we stored the value of the parameter count in the $arg variable—we did so in order to make the script a bit more efficient because otherwise we would have had to perform a call to func_get_args() for every cycle of the for loop. That would have been rather wasteful because a function call is quite expensive in terms of performance and the number of parameters passed to the function does not change during its execution.

Variable Variables  and Variable  Functions
PHP supports two very useful features known as variable variables and variable functions.
The former allows you use the value of a variable as the name of a variable. Sound confusing? Look at this example:

<?php
$x = 100;
$y = ‘x’;
echo $$y;
?>

When this script is executed and the interpreter encounters the $$y expression, it first determines the value of $y, which is the string a. It then reevaluates the expression with a substituted for $y as $x, thus returning the value of the $x variable. Similarly, you can use a variable’s value as the name of a function:

<?php
function odd_number ($x)
{
echo “$x is odd”;
}
function even_number ($x)
{
echo “$x is even”;
}
$n = 15;
$a = ($n % 2 ? ‘odd_number’ : ‘even_number’);
$a($n);
?>
At the end of the script, $a will contain either odd_number or even_number. The expression $a($n) will then be evaluated as a call to either odd_number() or even_number(). Variable variables and variable functions can be tremendously valuable and convenient. However, they tend to make your code obscure because the only way to really tell what happens during the script’s execution is to execute it—you can’t determine whether what you have written is correct by simply looking at it. As a result, you should only really use variable variables and functions when their usefulness outweighs the potential problems that they can introduce.

Share/Bookmark

0 comments:

Post a Comment