class FetchService
{
public function getById($id)
{
if (true) {
// Read be careful, i'm not passing array
$this->exitBrowser("[%s] 🔔 id is invalid format (%s)",
now()->toTimeString(),
$id,
);
}
}
public function exitBrowser(...$params)
{
$this->dddd(...$params);
$this->browser->quit();
$this->browser->stop();
}
public function dddd(...$params)
{
dump(sprintf(...$params));
}
}
$fetch = new FetchService();
$fetch->getById('something wrong');
//result
[21:00:00] 🔔 id is invalid format (something wrong)
Why keep passing ...$params and this sprintf(...$params) work?
The ... operator (called rest or splat in other languages) can be used for variadic functions, i.e. where the function can accept variable numbers of arguments.
It is also usable as a spread operator to unpack arrays or traversables into function parameters, or spread into other arrays, e.g.
@newbie360 yes, I explained that the spread operation unpacks arrays or traversables into function parameters. The exitBrowser function is passed three parameters:
"[%s] 🔔 id is invalid format (%s)"
now()->toTimeString()
$id
In the function's signature, they are packed into the $params array. However, they are then unpacked again (using ...) whenever you call sprintf
The `...$params` syntax is called the "splat" or "variadic" operator in PHP, which allows you to pass an arbitrary number of arguments to a function. Here's what's happening in your code:
### Key Concepts:
1. **Variadic Functions (`...$params`)**:
- In both the `exitBrowser` and `dddd` methods, `...$params` is used to collect any number of arguments passed to the method. These arguments are gathered into an array.
- When you call `exitBrowser("[%s] 🔔 id is invalid format (%s)", now()->toTimeString(), $id);`, the arguments are passed into `exitBrowser` as an array:
```php
[
"[%s] 🔔 id is invalid format (%s)",
now()->toTimeString(),
$id
]
```
2. **Passing Arguments to `sprintf`**:
- The `dddd` method uses `sprintf(...$params)` where `...$params` "unpacks" the array of arguments into individual parameters for `sprintf`. It is equivalent to calling:
```php
sprintf("[%s] 🔔 id is invalid format (%s)", "21:00:00", "something wrong");
```
- The `sprintf` function takes a format string as the first argument, followed by values to replace the placeholders (`%s` in this case). It formats the string accordingly.
3. **Why It Works**:
- The variadic operator (`...`) in the `dddd` method allows you to pass all collected arguments (`$params`) to `sprintf` dynamically.
- Without `...`, you would need to manually pass each argument, which is less flexible for handling an arbitrary number of inputs.
### Summary:
- `...$params` in the method signature collects arguments into an array.
- `sprintf(...$params)` unpacks the array back into separate arguments for `sprintf`, which processes the format string and its values.