Sunday, May 1, 2011

checking if a class is instance of another

i want to check if a class is an instance 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 its of a specific class family (to prevent security issues an such). any good way of doing this?

From stackoverflow
  • Are you trying to determine whether two objects have the same class, or whether two objects are effectively equivalent? These are semantically different operations.

  • 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";
    
  • 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.

  • 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);
    }
    
    sirlancelot : http://php.net/is_a
    Alex Barrett : is_a() works with instances of objects, and not the names of the classes themselves.

0 comments:

Post a Comment