PHP Function Default Parameters

Description

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

Syntax

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


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

Example

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


<?PHP//  w  ww.  j ava 2s.c o m
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//from   w w  w. j a  va  2s.  com
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) { } 




















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition