Default Arguments
In PHP, you can define default arguments for functions. Default arguments are values that a function will use if the caller doesn’t provide a value for that argument. This feature is useful when you want to make some function parameters optional.
Here’s how you can define default arguments in a PHP function:
phpCopy code
function myFunction($param1, $param2 = “default_value”) { // Function body // $param2 will use “default_value” if not provided by the caller }
In the example above:
- myFunction is the name of the function.
- $param1 is a required parameter that must be provided when calling the function.
- $param2 is an optional parameter with a default value of “default_value”. If the caller doesn’t provide a value for $param2, it will automatically use “default_value”.
Here are some usage examples:
phpCopy code
myFunction(“value1”); // $param1 = “value1”, $param2 = “default_value” myFunction(“value1”, “custom_value”); // $param1 = “value1”, $param2 = “custom_value”
In the first call, since we only provide one argument, $param1 gets “value1”, and $param2 uses the default value “default_value”.
In the second call, both arguments are provided, so $param1 gets “value1”, and $param2 gets “custom_value”.
Default arguments are a convenient way to make your functions more flexible and user-friendly, allowing callers to omit optional parameters while still providing reasonable default behavior.