Home > Article > Backend Development > Optional parameters in PHP
php editor Apple will introduce to you the optional parameters in PHP today. In PHP functions, we can define some parameters as optional parameters, so that all parameters do not need to be passed in when calling the function, thereby achieving more flexible function calling. Through the introduction of this article, you will understand how to define and use optional parameters in PHP functions, as well as precautions and common use cases. Let’s take a closer look at the optional parameters in PHP functions!
"NULL"
as optional parameter
We will create a function and pass it a default parameter
with its value set to "null"
. If we call the function without resetting the default parameter value, "null"
will be used instead.
<?php function fruits($bestfruit = "NULL") { return "I love enjoying $bestfruit" .'<br>'; } echo fruits(); echo fruits('manGo'); ?>
Output:
I love enjoying NULL I love enjoying mango
We will create a function and pass it a default parameter and set its value to String. If we call the function without resetting the default parameter value, then the specified value will be used instead of it.
<?php function fruits($bestfruit = "Apple") { return "I love enjoying $bestfruit" .'<br>'; } echo fruits(); echo fruits('mango'); ?>
Output:
I love enjoying Apple I love enjoying mango
Create a function and pass a default parameter and set its value to the empty string.
<?php function fruits($bestfruit = "") { return "I love enjoying $bestfruit" .'<br>'; } echo fruits(); echo fruits('PineApples'); ?>
Output:
I love enjoying I love enjoying PineApples
using the Splat operator (
...
Here we are not passing any default value. Instead, we will pass the splat operator (...
), which will default to an empty array when no arguments are passed to the function.
<?php function fruits(...$bestfruit) { var_dump($bestfruit).'<br>'; } echo fruits(); echo fruits('PineApples','test'); ?>
Output:
array(0) { } array(2) { [0]=> string(10) "PineApples" [1]=> string(4) "test" }
func_get_args
method to set optional parameters in PHP
Same as using the splat operator (...
), we create a function without passing any default value. If we call the function without specifying a value, 0
will be the default value.
<?php function summation() { $numbers = func_get_args(); return array_sum($numbers); } echo summation().'<br>'; echo summation(1,2,3,4,5,6); ?>
Output:
0 21
The above is the detailed content of Optional parameters in PHP. For more information, please follow other related articles on the PHP Chinese website!