PHP:判断类是否是另一个类的扩展
如何测试一个类是否通过名称扩展了另一个类?
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
}
How do you test to see if a class extends another class 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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想
这就是你要找的。这将返回父类的名称。
http://www.php.net/manual/en/function .get-parent-class.php
I think
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
我认为 class_parents 函数将是最简单的解决方案,但需要注意的是,这仅在 PHP 5.1 及更高版本中可用。
例如,如果您想查看“B”是否扩展了“A”,您可以使用:
顺便说一句,应该注意的是,根据文档,您可以提供一个对象(类实例)或一个字符串(类名)来
class_parents
函数,这可能很有用。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:
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.根据您要查找的内容,您可能还需要
instanceof
运算符。如果
$a
是类A
或任何扩展A
的类的实例,则$a instanceof A
将为 true > (包括如果它是扩展B
的C
实例,而B
扩展了A
)或实现了 A
(如果您使用的是接口)。请参阅 http://php.net/instanceofDepending what you're looking for you might also want the
instanceof
operator.$a instanceof A
will be true if$a
is an instance of classA
, or any class which extendsA
(including if it is an instance ofC
which extendsB
which extendsA
) or whichimplements A
(if you are using interfaces). See http://php.net/instanceof