Checking if a class is a subclass of another

19,642

Solution 1

is_subclass_of() will correctly check if a class extends another class, but will not return true if the two parameters are the same (is_subclass_of('Foo', 'Foo') will be false).

A simple equality check will add the functionality you require.

function is_class_a($a, $b)
{
    return $a == $b || is_subclass_of($a, $b);
}

Solution 2

Check out is_subclass_of(). As of PHP5, it accepts both parameters as strings.

You can also use instanceof, It will return true if the class or any of its descendants matches.

Solution 3

Yup, with Reflection

<?php

class a{}

class b extends a{}

$r = new ReflectionClass( 'b' );

echo "class b "
    , (( $r->isSubclassOf( new ReflectionClass( 'a' ) ) ) ? "is" : "is not")
    , " a subclass of a";

Solution 4

You can use is_a() with the third parameter $allow_string that has been added in PHP 5.3.9. It allows a string as first parameter which is treated as class name:

Example:

interface I {}
class A {}
class B {}
class C extends A implements I {}

var_dump(
    is_a('C', 'C', true),
    is_a('C', 'I', true),
    is_a('C', 'A', true),
    is_a('C', 'B', true)
);

Output:

bool(true)
bool(true)
bool(true)
bool(false)

Demo: http://3v4l.org/pGBkf

Share:
19,642

Related videos on Youtube

AriehGlazer
Author by

AriehGlazer

Updated on June 03, 2020

Comments

  • AriehGlazer
    AriehGlazer almost 4 years

    I want to check if a class is a subclass of another without creating an instance. I have a class that receives as a parameter a class name, and as a part of the validation process, I want to check if it's of a specific class family (to prevent security issues and such). Any good way of doing this?

    • Chad Birch
      Chad Birch about 15 years
      The way this is written is confusing, the question is actually for a way to determine if one class is a sub-class of another.
  • Alex Barrett
    Alex Barrett about 15 years
    is_a() works with instances of objects, and not the names of the classes themselves.
  • mae
    mae over 7 years
    This doesn't work with relatively namespaced classes. For example is_class_a('stdClass','\stdClass') will return FALSE even though they are one and the same.
  • Tom Auger
    Tom Auger over 7 years
    Use instanceof as per @sirlancelot's answer below stackoverflow.com/a/782741/467386