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?
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
Python issubclass() This function is used to check whether a class is a subclass of another class.
Can an object be a subclass of another object? A. Yes—as long as single inheritance is followed.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With