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, ..?
Start off with an
interfacethat defines the common methodsYour
CommonRepositoryclass should be anabstractclass that implements the interface and common methodsNow your repository classes can extend the
CommonRepositorybut still implement the interfaceFinally your function can take the interface as an argument so that any class instantiations passed in must be of that type