开发者

PHP: Determine whether class is extension of another class

开发者 https://www.devze.com 2023-03-07 02:42 出处:网络
How do you test to see if a class extends another clas开发者_C百科s by name? class A { ... } class B extends A { ... }

How do you test to see if a class extends another clas开发者_C百科s by name?

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

$class_name = 'B';
if (class_extends_another($class_name, 'A')) {
   // Yep
}

$class_name = 'C';
if (class_extends_another($class_name, 'A')) {
   // Nope
}


I think

get_parent_class()

is what you're looking for. Which will return the name of the parent class.

http://www.php.net/manual/en/function.get-parent-class.php


I've have thought that the class_parents function would be the simplest solution, although it should be noted that this is only available in PHP 5.1 and above.

For example, if you wanted to see if 'B' extended 'A', you could use:

if(in_array('A', class_parents('B'))) {
    // B extends A.
}

Incidentally, it should be noted that as per the docs you can provide either an object (class instance) or a string (class name) to the class_parents function, which may prove useful.


Depending what you're looking for you might also want the instanceof operator.

$a instanceof A will be true if $a is an instance of class A, or any class which extends A (including if it is an instance of C which extends B which extends A) or which implements A (if you are using interfaces). See http://php.net/instanceof

0

精彩评论

暂无评论...
验证码 换一张
取 消