tags:

views:

268

answers:

4

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?

A: 

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

Rob
+5  A: 

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";
Peter Bailey
+3  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.

sirlancelot
A: 

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