PHP Tutorial - PHP Function Parameter






PHP functions can optionally accept one or more arguments, which are values passed to the function.

A parameter is a variable that holds the value passed to it when the function is called.

Syntax

To specify parameters for your function, insert one or more variable names between the parentheses, as follows:

function myFunc( $oneParameter, $anotherParameter,... ) { 
  // (do stuff here) 
}  

Example - Add parameter to a function

We need to give each parameter a name to refer to it inside the function. PHP will copy the values it receives into these parameters:

<?PHP
function multiply($num1, $num2) { 
        $total = $num1 * $num2; 
        print $num1;
        print "\n";
        print $num2;
        return $total; 
} 
$mynum = multiply(5, 10); 
echo $mynum;
?>

The code above generates the following result.





Example

The following code shows how to create a definition list from a function.

<!DOCTYPE html>
<html>
  <body>
    <h2>A function to create a definition list</h2>
    <?php
    
    $iterations = 10;
    
    function defList( $contents ) {
      $markup = "<dl>\n";
    
      foreach ( $contents as $key => $value ) {
        $markup .= "  <dt>$key</dt><dd>$value</dd>\n";
      }
    
      $markup .= "</dl>\n";
      return $markup;
    }
    
    $myBook = array( "title" => "The Grapes of Wrath",
                     "author" => "John Steinbeck",
                     "pubYear" => 1939 );
    
    echo defList( $myBook );
    
    ?>

  </body>
</html>


The code above generates the following result.





PHP Function Default Parameters

Default parameter can have a value if the corresponding argument is not passed when the function is called.

PHP lets you create functions with optional parameters. You define an optional parameter as follows:

function myFunc( $parameterName=defaultValue ) { 
  // (do stuff here) 
}   

To define default parameters for a function, add the default value after the variables.

<?PHP
function doHello($Name = "java2s.com") { 
       return "Hello $Name!\n"; 
} 

doHello(); 
doHello("PHP"); 
doHello("java2s.com"); 
?>

Consider this function:

function doHello($FirstName, $LastName = "Smith") { } 

Only $LastName gets the default value. To provide default values for both parameters we have to define them separately.

<?PHP
function doHello($FirstName = "java2s", $LastName = ".com") { 
   return "Hello, $FirstName $LastName!\n"; 
} 
doHello(); 
doHello("java2s", ".com"); 
doHello("Tom"); 
?>

For a single parameter PHP will assume the parameter you provided was for the first name, as it fills its parameters from left to right.

We cannot put a default value before a non-default value. The following code is wrong.

function doHello($FirstName = "Joe", $LastName) { } 

Example - optional arguments

The following code shows how to create a function with optional arguments.

<?php

function calcSalesTax($price, $tax="") 
{
    $total = $price + ($price * $tax);
    echo "Total cost: $total";
}

calcSalesTax(42.00);

?>


The code above generates the following result.

PHP Variable Length Parameter

A function with variable-length parameter list can take as many parameters as user want.

We can use three functions to make a function handle variable length parameters.

  • func_num_args()
  • func_get_arg(), and
  • func_get_args()

func_num_args() and func_get_args() take no parameters.

  • func_num_args() gets the number of arguments passed into your function.
  • func_get_arg() gets the value of an individual parameter.
  • func_get_args() returns an array of the parameters that were passed in.

Here's an example:

<?PHP
function some_func($a, $b) { 
        for ($i = 0; $i < func_num_args(); ++$i) { 
                $param = func_get_arg($i); 
                echo "Received parameter $param.\n"; 
        } 
} 

function some_other_func($a, $b) { 
        $param = func_get_args(); 
        $param = join(", ", $param); 
        echo "Received parameters: $param.\n"; 
} 

some_func(1,2,3,4,5,6,7,8); 
some_other_func(1,2,3,4,5,6,7,8); 
?>

The code above generates the following result.

Example - variable number of argument

The following code shows how to create Function with variable number of argument.


<?php
  function makeList()
  {
    print("<ol>\n");
    for($i=0; $i < func_num_args(); $i++)
    {
      print("<li>" . func_get_arg($i) . "</li>\n");
    }
    print("</ol>\n");
  }

  makeList("Linux", "Apache", "MySQL", "PHP");
?>


The code above generates the following result.

PHP Function Reference Parameter

A reference is a pointer to a PHP variable.

Syntax to create reference variable

$myRef = &$myVariable;

Reference variable

We have two ways to read or change the variable's contents. We can use the variable name, or you can use the reference.

Here's a simple example that creates a reference to a variable:

<?PHP
         $myVar = 123; 
         $myRef = &$myVar; 
         $myRef++; 
         echo $myRef . "\n";  // Displays "124" 
         echo $myVar . "\n";  // Displays "124"   
?>

The code above generates the following result.

First a new variable, $myVar, is initialized with the value 123. Next, a reference to $myVar is created, and the reference is stored in the variable $myRef.

Note the ampersand (&) symbol after the equals sign; using this symbol creates the reference.

Because $myRef actually points to the same data. The next line of code adds one to the value of as $myVar, both $myRef and $myVar now contain the value 124.

Syntax for reference parameters

To get a function to accept an argument as a reference rather than a value, put an ampersand (&) before the parameter name within the function definition:

function myFunc(  & $aReference ){ 
  // (do stuff with $aReference) 
}   

Note

By passing a reference to a variable as an argument to a function, rather than the variable itself, you pass the argument by reference , rather than by value.

This means that the function can now alter the original value, rather than working on a copy.

Example 1

Reference parameter

<?PHP
    function resetCounter(  & $c ) { 
      $c = 0; 
    } 

    $counter = 0; 
    $counter++; 
    $counter++; 
    $counter++; 
    echo "$counter\n";  // Displays "3" 
    resetCounter( $counter ); 
    echo "$counter\n";  // Displays "0"   
?>

The code above generates the following result.

Example 2

The following code shows how to pass arguments by reference.

<?php

    $cost = 20.99;
    $tax = 0.0575;

    function calculateCost(&$cost, $tax)
    {
        // Modify the $cost variable
        $cost = $cost + ($cost * $tax);

        // Perform some random change to the $tax variable.
        $tax += 4;
    }
    calculateCost($cost, $tax);
    printf("Tax is %01.2f%% ", $tax*100);
    printf("Cost is: $%01.2f", $cost);

?>


The code above generates the following result.