Are there any best practices for handling optional parameters in PHP functions?
When handling optional parameters in PHP functions, it is a good practice to set default values for those parameters to avoid potential errors when the parameter is not provided. This ensures that the function can still be called without all parameters being passed. One way to handle optional parameters is by using the null coalescing operator (??) to assign a default value to the parameter if it is not provided.
function greet($name, $message = 'Hello') {
echo "$message, $name!";
}
// Calling the function with only the required parameter
greet('John'); // Output: Hello, John!
// Calling the function with both parameters
greet('Jane', 'Hi'); // Output: Hi, Jane!