Steve
Steve

Reputation: 1963

How can I force a group of classes to require a method with variable paramters

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 Collection

abstract class Collection
{
  abstract public function add ($id, $name);
}

Box Collection

class BoxCollection extends Collection
{
  public function add ($id, $name, $color)
  {
    $this->data[] = compact('id', 'name', 'color');
  }
}

Shape Collection

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

Answers (2)

Jarek.D
Jarek.D

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

ze_iliasgr
ze_iliasgr

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

Related Questions