Q Explain "..." or "splat" or "variadic" operator in php.
Answer:
In PHP, the ... (three dots) syntax is known as the "splat" or "variadic" operator. It is used in the context of function parameters to allow a variable number of arguments to be passed to a function. This feature was introduced in PHP 5.6.
When you use ... in the function parameter list, it allows the function to accept an arbitrary number of arguments. These arguments are then bundled into an array, which can be accessed within the function. Here's a simple example:
function exampleFunction(...$args) {
foreach ($args as $arg) {
echo $arg . ' ';
}
}
exampleFunction('apple', 'banana', 'cherry');
In this example, exampleFunction accepts any number of arguments, and the arguments are collected into the $args array. The function then iterates over the array and echoes each argument.
You can also use the splat operator with a specific type:
function exampleFunction(string ...$args) {
foreach ($args as $arg) {
echo $arg . ' ';
}
}
exampleFunction('apple', 'banana', 'cherry');
In this case, the function expects each argument to be of type string.
Keep in mind that the splat operator must be the last parameter in the function parameter list, and a function can have only one variadic parameter.
No comments:
Post a Comment