PHP Tutorial - PHP Function






A function is a self contained block of code that performs a specific task.

Functions avoid duplicating code. They make it easier to eliminate errors.

Functions can be reused in other scripts. They help you break down a big project.

Parameter

A function often accepts one or more arguments, which are values passed to the function by the code that calls it.

The function can then read and work on those arguments.

Return

A function may optionally return a value that can then be read by the calling code.

In this way, the calling code can communicate with the function.





PHP Function Create

We define functions with the function keyword, followed by the name of the function and two parentheses.

The actual code your function will execute lies between braces.

Defining a function use the following syntax:

function myFunc() { 
   // (do stuff here) 
}   

Example - define a function

Define a function

<?PHP
         function hello() { 
            echo "Hello, world!\n"; 
         } 
         hello(); 
?>

The code above generates the following result.

As you can see, this script defines a function, hello() , that simply displays the string "Hello, world! "

The code within the hello() function is only run when the function is later called, not when the function itself is created.





PHP Function Return

Function can return one value back from functions by using the return statement.

If you try to assign to a variable the return value of a function that has no return value, your variable will be set to NULL.

Example - return value from a function

Return value from a function

<?PHP
function foo() { 
       print "In function"; 
       return 1; 
       print "Leaving function..."; 
} 
print foo(); 
?>

The code above generates the following result.

PHP Return Reference

As well as passing variables by reference into functions, you can also get functions to return references, rather than values.

Place an ampersand before the function name in your function definition. Then, when you return a variable with the return statement, you pass a reference to that variable back to the calling code, rather than the variable ' s value:

function  &myFunc(){ 
    // (do stuff) 
   return $var;  // Returns a reference to $var 
}   

Return reference from a function

<?PHP
   $myNumber = 5; 

   function  &getMyNumber() { 
     global $myNumber; 
     return $myNumber; 
   } 

   $numberRef = &getMyNumber(); 
   $numberRef++; 
   echo "\$myNumber = $myNumber\n";   // Displays "6" 
   echo "\$numberRef = $numberRef\n"; // Displays "6"   
?>

The code above generates the following result.

PHP Recursive Functions

A recursive function is a function which call itself.

Here's a quick overview of how a recursive function operates:

The recursive function is called by the calling code If the base case is met, the function does required calculation, then exits.

Otherwise, the function does required calculation, then calls itself to continue the recursion.

Here is an example to calculate factorials:

<?PHP
function factorial($number) { 
        if ($number == 0) return 1; 
        return $number * factorial($number-1); 
} 

print factorial(6); 
?>

The code above generates the following result.

Example - A PHP recursive function

The following code shows how to create recursive function.


<?php
  function checkInteger($Number)
  {
    if($Number > 1)
    {
      // integer minus one is still an integer
      return(checkInteger($Number-1));
    }
    elseif($Number < 0)
    {
      //numbers are symmetrical, so
      //check positive version
      return(checkInteger((-1)*$Number-1));
    }
    else
    {
      if(($Number > 0) AND ($Number < 1))
      {
        return("no");
      }
      else
      {
        //zero and one are
        //integers by definition
        return("yes");
      }
    }
  }

  print("Is 0 an integer? " .  checkInteger(0) . "<br>\n");
  print("Is 7 an integer? " . checkInteger(7) . "<br>\n");
  print("And 3.5? " . checkInteger(3.5) . "<br>\n");
  print("What about -5? " . checkInteger(-5) . "<br>\n");
  print("And -9.2? " . checkInteger(-9.2) . "<br>\n");
?>


The code above generates the following result.

PHP Anonymous Function

PHP anonymous functions have no name.

You might want to create anonymous functions for two reasons:

  • To create functions dynamically
  • To create short-term, disposable functions

Syntax

To create an anonymous function, you use separated list of parameters if any, and the code for the function body.

$myFunction = create_function( '$param1, $param2', 'function code here;' );

Example for anonymous function

Here's an example that creates an anonymous function dynamically based on the value of a variable:

<?PHP
        $mode = "+"; 
        $processNumbers = create_function( '$a, $b', "return \$a $mode \$b;" ); 
        echo $processNumbers( 2, 3 ); // Displays "5"   
?>

The code above generates the following result.

This code uses the value of the $mode variable as the operator used to process its two arguments, $a and $b. For example, if you change $mode to "*", the code displays "6".

Example - dynamical function

The following code shows how to call a function dynamically.

<?php
  function write($text)
  {
    print($text);
  }

  function writeBold($text)
  {
    print("<b>$text</b>");
  }

  $myFunction = "write";
  $myFunction("Hello!");
  print("<br>\n");

  $myFunction = "writeBold";
  $myFunction("Goodbye!");
  print("<br>\n");
?>


The code above generates the following result.