PHP Functions

In addition the built-in PHP functions, we can create our own functions.

A function is a block of statements that can be used frequently in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.


User Defined Function in PHP :-


A user defined function statement starts with the word “function":
                                function functionname()
                                            {
                                                code to be executed;
                                            }

A valid function name starts with a letter or underscore-
Example : 
      
<?php

function msg()
{
echo "Hello world!";
}

    msg(); // call the function
?>

Function Arguments in PHP :-

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.
PHP supports passing arguments by value (the default), passing by reference, and default argument values.

Example - Passing arrays to functions.

<?php
function takes_array($input)
{
                  echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>

Making arguments be passed by reference :

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:

Example - Passing function parameters by reference.

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

Default argument values :

A function may define C++-style default values for scalar arguments as follows:

Example - Use of default parameters in functions.

<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
   echo makecoffee();
   echo makecoffee(null);
   echo makecoffee("espresso");
?>

Functions - Returning values :-

To let a function return a value, use the return statement: 
Example :
<?php
          function sum($x,$y)
                   {
                     $z=$x+$y;
                    return $z;
                  }

echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>

Anonymous functions :

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.
Example - Anonymous function example.

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
     return strtoupper($match[1]);
  }, 'hello-world');
// outputs helloWorld
?>

Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon:

Example - Anonymous function variable assignment example.

<?php
                 $greet = function($name)
                      {
                           printf("Hello %s\r\n", $name);
                      };

         $greet('World');
         $greet('PHP');
?>

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:

Example - Closures and scoping.

<?php
// A basic shopping cart which contains a list of added products
// and the quantity of each product. Includes a method which
// calculates the total price of the items in the cart using a
// closure as a callback.
class Cart
{
    const PRICE_BUTTER  = 1.00;
    const PRICE_MILK    = 3.00;
    const PRICE_EGGS    = 6.95;

    protected $products = array();
   
    public function add($product, $quantity)
    {
        $this->products[$product] = $quantity;
    }
   
    public function getQuantity($product)
    {
        return isset($this->products[$product]) ? $this->products[$product] :
               FALSE;
    }
   
    public function getTotal($tax)
    {
        $total = 0.00;
       
        $callback =
            function ($quantity, $product) use ($tax, &$total)
            {
                $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                    strtoupper($product));
                $total += ($pricePerItem * $quantity) * ($tax + 1.0);
            };
       
        array_walk($this->products, $callback);
        return round($total, 2);
    }
}

$my_cart = new Cart;

// Add some items to the cart
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);

// Print the total with a 5% sales tax.
print $my_cart->getTotal(0.05) . "\n";
// The result is 54.29
?>

More Details :  http://www.php.net/manual/en/functions.anonymous.php
   

Comments