In PHP, functions can accept parameters with default values. These default values are specified in the function declaration, and when calling the function, if the corresponding parameter is omitted, the default value is used.
The syntax to set default values in PHP is as follows:
<span class="fun">function function_name(type $parameter1 = default_value, type $parameter2 = default_value, ...): return_type;</span>
For example, here's a function where the second parameter has a default value:
<span class="fun">function sum($a, $b = 0, $c)</span>
This function accepts three parameters, with $b having a default value of 0. When calling the function, if no value is provided for $b, it will automatically use the default value of 0.
Next, let's write a function that accepts a number and returns its square. If no number is provided, it will use the default value of 10:
<span class="fun">function square($number = 10)</span>
Here is the complete function code:
<span class="fun">function square($number = 10) { return $number * $number; }</span>
You can call this function as follows:
<span class="fun">echo square(); // Output: 100</span>
<span class="fun">echo square(5); // Output: 25</span>
In the first call, no parameter is provided, so it uses the default value of 10. In the second call, the number 5 is provided, so it returns the square of 5.
In PHP, function parameter default values make functions more flexible by handling different argument scenarios. By using default values properly, we can avoid manually checking if a parameter is empty, simplifying our code.