PHP: Restrict class type in function parameter

132 Views Asked by At

I have inherited some code like this

    public static function instanciateRepository( $repositoryClass, ... ) {
...
        new $repositoryClass( ... );
    }

Where $repositoryClass is a class type that needs to be instanciated.

I want to add a syntax check for passing a wrong class argument to this function, specifically limit $repositoryClass to sublasses of CommonRepository. Is there a syntax construction to achieve that in PHP, e.g. instanciateRepository( CommonRepository::class $repositoryClass, ..?

1

There are 1 best solutions below

1
mark_b On

Start off with an interface that defines the common methods

interface CommonRepositoryInterface {}

Your CommonRepository class should be an abstract class that implements the interface and common methods

abstract class CommonRepository implements CommonRepositoryInterface {}

Now your repository classes can extend the CommonRepository but still implement the interface

final class RepositoryClass extends CommonRepository {}

Finally your function can take the interface as an argument so that any class instantiations passed in must be of that type

public static function instanciateRepository(CommonRepositoryInterface $repositoryClass, ... ) {}