PHP Function Default Parameters
In this chapter you will learn:
- What is PHP Function Default Parameters
- Syntax for PHP Function Default Parameters
- 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: