DEV Community

Sébastien NOBILI
Sébastien NOBILI

Posted on • Originally published at techreads.pipoprods.org

PHP: How to declare the expected type for an array to pass to an abstract method

PHP arrays may host mixed content. The language processor won't complain if you write this:

$list = [
  'some-string', 
  3,
  [ 'key' => 'value' ]
];
Enter fullscreen mode Exit fullscreen mode

That can be useful in many cases but what if you want to declare an abstract method and indicate to developers what it should get?

abstract class MyClass {
  public abstract function my_function($args);
}
Enter fullscreen mode Exit fullscreen mode

First approach: make the developer aware of the type

Adding a comment is enough to tell the developers what your method expect:

abstract class MyClass {
  /**
   * This method will process a list of objects.
   *
   * @param MyObjects[] $args
   */
    public abstract static function my_function($args);
}
Enter fullscreen mode Exit fullscreen mode

Second approach: make PHP aware of the type

Declaring the argumens as an array is not enough, as it won't indicate the type of what should be inside the array:

public abstract static function my_function(array $args);
Enter fullscreen mode Exit fullscreen mode

We'll have to transform the array argument into a variable list of MyObject arguments:

public abstract static function my_function(MyObject ...$args);
Enter fullscreen mode Exit fullscreen mode

On the caller side, the syntax will need to be changed to spread the arrray:

$result = MyClass::my_function(...$array_of_objects);
Enter fullscreen mode Exit fullscreen mode

Final thoughts

Both approaches can (and should) be mixed: add comments for the developers & make PHP aware of the type.

This implementation makes it easier to follow the types of the variables that are passed across the code but it has a drawback.
By declaring a variable list of arguments to a method, you won't be able to pass multiple lists of different types to it.

Top comments (0)