ddinchev
ddinchev

Reputation: 34673

How can I check if a string is the name of a sub class of a specific class?

I want to check that string passed to a function would result in instance of certain class or subclass of it. The following example does the trick but I'm looking for a solution that does not require you to instantiate $className - as I actually do not really need it.

public function register($className, $baseAttributes) {
    $instance = new $className;
    if (!($instance instanceof AbstractFoo)) {
        throw new InvalidArgumentException();   
    }
    ...
}

I have another method that factors instances of $className but I want to fail as early as possible if wrong class has been supplied to the method during configuration. For example something like:

public function register($className, $baseAttributes) {
    if (!($className classof AbstractFoo)) {
        throw new InvalidArgumentException();   
    }
    ...
}

Upvotes: 3

Views: 117

Answers (2)

deceze
deceze

Reputation: 522332

if ($className == 'AbstractFoo' || is_subclass_of($className, 'AbstractFoo')) …

See http://php.net/is_subclass_of.

If AbstractFoo is indeed abstract you can in fact skip the first equality check, since it will never be true.

Upvotes: 2

Haresh Vidja
Haresh Vidja

Reputation: 8496

Well, you need Reflection, and two methods getParentClass() & isAbstract().

Here's a working example of what you need.

public function register($className, $baseAttributes) {

     $classReflection = new ReflectionClass($className);
     $parentClassName = $classReflection->getParentClass()->getName();
     if($parentClassName=="AbstractFoo"){
          throw new InvalidArgumentException();   
     }

     $parentReflection = new ReflectionClass($parentClassName);

     $isAbstract= $parentReflection->isAbstract(); // return true of false
     if (!($isAbstract)) {
          throw new InvalidArgumentException();   
     }
     //....
}

Other Solution using isSubclassOf() method of ReflectionClass

 public function register($className, $baseAttributes) {
     $classReflection = new ReflectionClass($className);
     if($classReflection->isSubclassOf("AbstractFoo")){
          throw new InvalidArgumentException();   
     }
     //....
}

Upvotes: 4

Related Questions