tags:

views:

41

answers:

3

Is there a way in PHP to know if one class inherits another?

class Controller
{
}

class HomeController extends Controller
{
}

class Dummy
{
}

// What I would like to do

    $result = class_extends('HomeController', 'Controller'); /// true
    $result = class_extends('Dummy', 'Controller'); /// false
+2  A: 

Yes, you can use

if ($foo instanceof ClassName)
    // do stuff...

EDIT: As far as I know, this should even work for interfaces...

Franz
Forget the implements stuff. I was losing it ;)
Franz
is there a way to not construct the object?
Daniel A. White
Yes, you can use `class_parents()` for that: http://de2.php.net/manual/de/function.class-parents.php
Franz
Same thing for interfaces: `class_implements()` - http://php.net/manual/function.class-implements.php
Franz
+1  A: 

May I recomment the instanceof operator?

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

$b = new B;
$c = new C;

var_dump($b instanceof A, $c instanceof A) // bool(true), bool(false)
Dereleased
+5  A: 

You need to use instanceof.

Note that implements is incorrect. instanceof should be used in both cases (checking whether an object is an inherited class, or whether the object implements an interface).

Example from manual:

<?php
interface MyInterface
{
}

class MyClass implements MyInterface
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>

gives:

bool(true)
bool(true)
zombat
Yeah, I know. I don't know what I was thinking. Late night here ;)
Franz
Ha ha... I was going to comment, but by the time I hit submit on my own, you had already fixed it. :D
zombat