Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a class is a subclass of another

Tags:

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?

like image 454
AriehGlazer Avatar asked Apr 23 '09 17:04

AriehGlazer


People also ask

How do you determine if a certain class is a subclass of another class Java?

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.

How do you know if a class is subclass of another class in Python?

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 class?

Can an object be a subclass of another object? A. Yes—as long as single inheritance is followed.


1 Answers

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); } 
like image 146
Alex Barrett Avatar answered Oct 29 '22 11:10

Alex Barrett