F
Filamentβ€’2w ago
ericmp

Which one would u use & why?

public function data(Closure|array $data): static
{
if (is_callable($data)) {
$this->data = call_user_func($data); // A
$this->data = $data(); // or B?
} else {
$this->data = $data;
}

return $this;
}
public function data(Closure|array $data): static
{
if (is_callable($data)) {
$this->data = call_user_func($data); // A
$this->data = $data(); // or B?
} else {
$this->data = $data;
}

return $this;
}
also, u see any improvements on this code, or is it okay?
8 Replies
Tetracyclic
Tetracyclicβ€’2w ago
Definitely B, there's no need to use call_user_func anymore I'd also opt for $data instanceof Closure instead of is_callable($data)
ericmp
ericmpβ€’2w ago
oh, okay. why though?
Tetracyclic
Tetracyclicβ€’2w ago
You could also simplify to:
public function data(Closure|array $data): static
{
$this->data = $data instanceof Closure ? $data() : $data;

return $this;
}
public function data(Closure|array $data): static
{
$this->data = $data instanceof Closure ? $data() : $data;

return $this;
}
Dennis Koch
Dennis Kochβ€’2w ago
Callables are more than Closures though
Tetracyclic
Tetracyclicβ€’2w ago
But the function only accepts a Closure or array
Dennis Koch
Dennis Kochβ€’2w ago
Well, it that case you are right πŸ˜…
ericmp
ericmpβ€’2w ago
i did a fast lookup on vendor/filament and search for call_user_func & also fir is_callable in my case havent found results but if i do search for instanceof Closure i do get results yeah ill follow yeah cool ill stick to this ty y'all for the feedback!
Tetracyclic
Tetracyclicβ€’2w ago
No problem!