Lesson 8: Function - TOP10

Lesson 8: Function

function is a self-contained block of code that can be called by your scripts. When called, the function's code is executed. You can pass values to functions, which will then work with them. When finished, a function can pass a value back to the calling code. Functions provide a way to group together related statements into a cohesive block. For reusable code, a function saves duplicating statements and makes maintenance of the code easier.


1. Defining a Function 

You can define a function using the function statement:
function some_function( $argument1, $argument2 ) { // function code here
}

The name of the function follows the function statement and precedes a set of parentheses. If your function requires arguments, you must place comma-separated variable names within the parentheses. These variables will be filled by the values passed to your function. Even if your function doesn't require arguments, you must nevertheless supply the parentheses. Example: A user-defined function to output bold text

<?php
 function bold($string)   {
   echo "<b>" . $string . "</b>\n";
 }
  // First example function call (with a static string)  
   echo "this is not bold\n";   bold("this is bold");  
   echo "this is again not bold\n";   // Second example function call (with a variable)  
   $myString = "this is bold";   bold($myString);
 ?>

The script defines the function bold( ), which takes one parameter, $string, and prints that string prefixed by a bold tag and suffixed with a tag. The bold( ) function, defined here, can be used with a string literal expression or a variable, as shown.

Functions can also return values. For example, consider the following code fragment that declares and uses a function heading( ), which returns a string using the return statement:

<?php   function heading($text, $headingLevel)   {  
switch ($headingLevel)    {    
case 1:      $result = "<h1>" . ucwords($text) . "</h1>";      break;     case 2:      $result = "<h2>" . ucwords($text) . "</h2>";      break;     case 3:      $result = "<h3>" . ucfirst($text) . "</h3>";      break;

default:      $result = "<p><b>" . ucfirst($text) . "</b>";     }    return($result);   }   $test = "user defined functions";   echo heading($test, 2);

?>

The function takes two parameters: the text of a heading and a heading level. Based on the value of $headingLevel, the function builds the HTML suitable to display the heading—changing the case of the $text appropriately. The previous fragment generates the string: <h2>User Defined Functions</h2> The variable that is returned by a return statement can optionally be placed in parentheses: the statements return($result) and return $result are identical.

2. Argument Types and Return Types

The argument and return types of a function aren't declared when the function is defined. PHP allows arguments of any type to be passed to the function, and as with variables, the return type is determined when a result is actually returned. Consider a simple function that divides two numbers:

function divide($a, $b) { return ($a/$b); } $c = divide(4, 2); // assigns an integer value = 2 $c = divide(3, 2); // assigns a float value = 1.5 $c = divide(4.0, 2.0); // assigns a float value = 2.0

3. Variable Scope

Variables used inside a function are different from those used outside a function. The variables used inside the function are limited to the scope of the function (there are exceptions to this rule, which are discussed later in this section). Consider an example that illustrates variable scope: function doublevalue($var) { $temp = $var * 2; } $variable = 5; doublevalue($variable); echo "\$temp is: $temp";
This example outputs the string: $temp is: and no value for $temp. The scope of the variable $temp is local to the function doublevalue( ) and is discarded when the function returns.
The PHP script engine doesn't complain about undeclared variable being used. It just assumes the variable is empty. However, this use of an undefined variable can be detected using the errorreporting settings discussed later.
If you want to use a value that is local to a function elsewhere in a script, the easiest way to do so is to return the value of the variable. This example achieves this: function doublevalue($var)


{
$returnVar = $var * 2; return($returnVar);
} $variable = 5; $temp = doublevalue($variable); echo "\$temp is: $temp";
The example prints: $temp is: 10
You could have still used the variable name $temp inside the function doublevalue( ). However, the $temp inside the function is a different variable from the $temp outside the function. The general rule is that variables used exclusively within functions are local to the function, regardless of whether an identically named variable is used elsewhere. There are two exceptions to this general rule: variables passed by reference and those declared global in the function aren't local to the function.
Global variables
 If you want to use the same variable everywhere in your code, including within functions, you can do so with the global statement. The global statement declares a variable within a function as being the same as the variable that is used outside of the function. Consider this example: function doublevalue( ) { global $temp; $temp = $temp * 2; } $temp = 5; doublevalue( ); echo "\$temp is: $temp"; Because $temp is declared inside the function as global, the variable $temp used in doublevalue() is a global variable that can be accessed outside the function. Because the variable $temp can be seen outside the function, the script prints: $temp is: 10
A word of caution: avoid overuse of global as it makes for confusing code. - The global variable declaration can be a trap. - In some other languages, global variables are usually declared global outside the functions and then used in the functions. - In PHP, it's the opposite: to use a global variable inside a function, declare the variable as global inside the function. An alternative to using global is to return more than one variable from a function by creating and returning an array of values. A better approach is to pass parameters by reference instead of by value. We discuss the latter approach in the next section.
4. How Variables Are Passed to Functions By default, variables are passed to functions by value, not by reference. The following example:  function doublevalue($var) { $var = $var * 2; } $variable = 5; doublevalue($variable);

echo "\$variable is: $variable";
has the output: $variable is: 5 The parameter $variable that is passed to the function doublevalue( ) isn't changed by the function. What actually happens is that the value 5 is passed to the function, doubled to be 10, and the result lost forever! The value is passed to the function, not the variable itself.
5.  Passing arguments by reference An alternative to returning a result or using a global variable is to pass a reference to a variable as an argument to the function. This means that any changes to the variable within the function affect the original variable. Consider this example:  <?php   function doublevalue(&$var) { $var = $var * 2; } $variable = 5; doublevalue($variable); echo "\$variable is: $variable"; ?>  This prints: $variable is: 10
The only difference between this example and the last one is that the parameter $var to the function doublevalue( ) is prefixed with an ampersand character: &$var. The ampersand means that a reference to the original variable is passed as the parameter, not just the value of the variable. The result is that changes to $var in the function affect the original variable $variable outside the function.
Functions that are defined with arguments that are references to variables can't be called with literal expressions, because the function expects a variable to modify. PHP reports an error when such a call is made.
6. Default argument values PHP allows functions to be defined with default values for arguments. A default value is simply supplied in the argument list using the = sign. Consider the modified heading( ) function described earlier:  <?php   function heading($text, $headingLevel = 2)   {    switch ($headingLevel)    {    case 1:     $result = "<h1>" . ucwords($text) . "</h1>";     break;    case 2:     $result = "<h2>" . ucwords($text) . "</h2>";     break;    case 3:     $result = "<h3>" . ucfirst($text) . "</h3>";

 break;    default:     $result = "<p><b>" . ucfirst($text) . "</b>";    }    return($result);   }   $test = "user defined functions";   echo heading($test);  ?>
When calls are made to the heading( ) function, the second argument can be omitted, and the default value 2 is assigned to the $headingLevel variable.
7. Calling a Function Functions in a PHP program can be either 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:  $some_value = function_name( [ parameter, ... ] );
The number of parameters a function requires differs from function to function.The parameters supplied to the function may be any valid expression and should be in the specific order expected by the function. 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
In the this 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.  


Previous
Next Post »