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
2009-04-23 17:05:42
+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
2009-04-23 17:07:14
+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
2009-04-23 17:20:24
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
2009-04-23 17:36:03
http://php.net/is_a
sirlancelot
2009-04-24 00:46:23
is_a() works with instances of objects, and not the names of the classes themselves.
Alex Barrett
2009-04-24 01:08:55