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


	      	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;
			?>
		  

Example


		  	<!DOCTYPE html>
			<html>
			  <body>
			    <h2>A function to create a definition list
			    <?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>
		  

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.


		  			  

Example - optional arguments


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

		  

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.

		  	<?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); 
			?>
		  


Example - 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", "HTML", "MySQL", "PHP");
			?>
		  

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.


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

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


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) 
			}  
		  

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.


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

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

		  	<?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);
			?>
		  




PHP Tutorials


Home

Introduction

Syntax

Variable

Comment

Echo and Print Statement

Data Types

Boolean

Integer

Number Convert

PHP String

php variable substitution in string

php string element

php string function

php addcslashes function

php addslashes function

php get magic quotes gpc function

php get meta tags function

php urlencode function

PHP $ and $$ Variables

PHP constant

PHP Magic Constants

PHP Static Variable

PHP Super Globals

PHP Globals

PHP Server

PHP reserved variable get

PHP reserved variable post

PHP reserved variable FILES

PHP reserved variable Cookies

PHP reserved variable Session

PHP reserved variable Request

PHP reserved variable environment

PHP Operator

PHP Arithmetic Operator

PHP Comparison Operator

PHP Incrementing and Decrementing Operators

PHP Identical Operators

PHP Logical Operators

PHP String Operators

PHP Ternary Operators

PHP Execution Operators

PHP Operator Precedence

PHP Array Operator

PHP Class

PHP Class Inheritance

PHP constructor and destructor

PHP abstract class

PHP class access control

PHP statement

PHP If statement

PHP else statement

PHP else if statement

PHP control structure statement

PHP while loop

PHP do while loop

PHP for loop

PHP for each loop

PHP break statement

PHP continue statement

PHP declare statement

PHP return statement

PHP require statement

PHP include

PHP require once

PHP include once

PHP goto statement

PHP function

PHP function parameter

PHP function scope

PHP array

PHP array operator

PHP array element loop

PHP array foreach loop

PHP array multidimensional

PHP html forms

PHP get and post method

form redirect

file inclusion