is_subclass_of
is_subclass_of
(PHP 4, PHP 5, PHP 7)
is_subclass_of - 检查对象是否将此类作为其父项之一或实现它。
描述
bool is_subclass_of ( mixed $object , string $class_name [, bool $allow_string = TRUE ] )
检查给定object
是否将该类class_name
作为其父项之一或实现它。
参数
object
类名称或对象实例。如果该类不存在,则不会生成错误。
class_name
类名称
allow_string
如果此参数设置为 false,object
则不允许使用字符串类名称。如果该类不存在,这也可以防止调用自动加载器。
返回值
该函数返回TRUE
如果对象object
,属于一类,这是的一个子类class_name
,FALSE
否则。
更新日志
Version | Description |
---|---|
5.3.9 | Added allow_string parameter |
5.3.7 | Added support for class_name to work with interfaces |
5.0.3 | You may also specify the object parameter as a string (the name of the class) |
例子
示例#1 is_subclass_of()示例
<?php
// define a class
class WidgetFactory
{
var $oink = 'moo';
}
// define a child class
class WidgetFactory_Child extends WidgetFactory
{
var $oink = 'oink';
}
// create a new object
$WF = new WidgetFactory(
$WFC = new WidgetFactory_Child(
if (is_subclass_of($WFC, 'WidgetFactory')) {
echo "yes, \$WFC is a subclass of WidgetFactory\n";
} else {
echo "no, \$WFC is not a subclass of WidgetFactory\n";
}
if (is_subclass_of($WF, 'WidgetFactory')) {
echo "yes, \$WF is a subclass of WidgetFactory\n";
} else {
echo "no, \$WF is not a subclass of WidgetFactory\n";
}
// usable only since PHP 5.0.3
if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
echo "yes, WidgetFactory_Child is a subclass of WidgetFactory\n";
} else {
echo "no, WidgetFactory_Child is not a subclass of WidgetFactory\n";
}
?>
上面的例子将输出:
yes, $WFC is a subclass of WidgetFactory
no, $WF is not a subclass of WidgetFactory
yes, WidgetFactory_Child is a subclass of WidgetFactory
示例#2使用接口示例的 is_subclass_of()
<?php
// Define the Interface
interface MyInterface
{
public function MyFunction(
}
// Define the class implementation of the interface
class MyClass implements MyInterface
{
public function MyFunction()
{
return "MyClass Implements MyInterface!";
}
}
// Instantiate the object
$my_object = new MyClass;
// Works since 5.3.7
// Test using the object instance of the class
if (is_subclass_of($my_object, 'MyInterface')) {
echo "Yes, \$my_object is a subclass of MyInterface\n";
} else {
echo "No, \$my_object is not a subclass of MyInterface\n";
}
// Test using a string of the class name
if (is_subclass_of('MyClass', 'MyInterface')) {
echo "Yes, MyClass is a subclass of MyInterface\n";
} else {
echo "No, MyClass is not a subclass of MyInterface\n";
}
?>
上面的例子将输出:
Yes, $my_object is a subclass of MyInterface
Yes, MyClass is a subclass of MyInterface
笔记
注意
:如果该类不是已知的,则使用此函数将使用任何已注册的自动加载器。
请参阅
- get_class() - 返回对象类的名称
- get_parent_class() - 检索对象或类的父类名称
- is_a() - 检查对象是否属于此类或者将此类作为其父类之一
- class_parents() - 返回给定类的父类
← is_a
method_exists →