Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for extends [closed]

I try to detect of one is extends by another, but it just doesn't work.. Can anyone point me in the right direction?

class Main
{
}

class Sub extends Main
{
}

class Third
{
}

$check = class_extends('Sub', 'Main'); // should return true
$check = class_extends('Third', 'Main'); // should return false

So is this possible, and if so, how?


2 Answers

You might be looking for is_subclass_of. Works with instances and string class names too, lets say you have these classes:

class B {}
class C extends B {}
class A {}

Then

var_dump(is_subclass_of('C', 'B')); // true, C is subclass of B
var_dump(is_subclass_of('C', 'A')); // false C is not subclass of A

Or if you like skinny arrows (->) you can use reflection too:

$refC = new ReflectionClass('C');
var_dump($refC->isSubclassOf('B')); // true, C is subclass of B
var_dump($refC->isSubclassOf('A')); // false C is not subclass of A
like image 158
complex857 Avatar answered Jul 19 '26 01:07

complex857


Yes this is possible. I think you where looking for instanceof.

$object = new Sub;
var_dump($object instanceof Main);

This will output bool(true).

Compare with the Example #3 Using instanceof to check if object is not an instanceof a class on php.net:

<?php
class MyClass
{
}

$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>
like image 29
Joran Den Houting Avatar answered Jul 19 '26 01:07

Joran Den Houting



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!