PHP Function Default Parameters

In this chapter you will learn:

  1. What is PHP Function Default Parameters
  2. Syntax for PHP Function Default Parameters
  3. Example - Create and use default parameter

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//j  a  v a  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 j  a  v a  2s .  c om
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) { } 

Next chapter...

What you will learn in the next chapter:

  1. What is Variable Length Parameter
  2. Support Functions
  3. Example - Use variable length parameters
Home » PHP Tutorial » PHP Function Create
PHP Function
PHP Function Create
PHP Function Parameter
PHP Function Default Parameters
PHP Variable Length Parameter
PHP Function Reference Parameter
PHP Function Return
PHP Return Reference
PHP Variable Scope in Functions
PHP Global Variables
PHP Recursive Functions
PHP Anonymous Function
PHP static variable