Reputation: 1963
My application has a group of similar classes that all require a method with a specific name, but the number of parameters is variable. Using an abstract or interface requires the extending/implementing class method to use the same number of parameters.
e.g. (this won't work but is essentially what I want to do)
abstract class Collection
{
abstract public function add ($id, $name);
}
class BoxCollection extends Collection
{
public function add ($id, $name, $color)
{
$this->data[] = compact('id', 'name', 'color');
}
}
class ShapeCollection extends Collection
{
public function add ($id, $name, $edges)
{
$this->data[] = compact('id', 'name', 'edges');
}
}
I know I could accept an associative array (potentially checking it and throwing an exception if required keys aren't present) but this doesn't help the dev when they are inputting the data, I want the IDE to be able to hint the required parameters.
Is there a way to achieve this behavior?
Upvotes: 0
Views: 122
Reputation: 1294
Use the ...
operator (available since php 5.6)
abstract class Collection
{
abstract public function add ($id, ...$params);
}
The concrete classes wouldn't need to be changed then at all
Upvotes: 0
Reputation: 193
In the BoxCollection::add
make the color
argument optional by adding a default value that makes sense. You won't get any errors then.
If in another class you want to give only the id
parameter to this method, give a default value to name
parameter, possibly null
will do.
Upvotes: 1