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?
-
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 returntrueif the two parameters are the same (is_subclass_of('Foo', 'Foo')will befalse).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_aAlex Barrett : is_a() works with instances of objects, and not the names of the classes themselves.
0 comments:
Post a Comment