首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[函数]is_a()函数—用法及示例

发布于 2025-04-18 10:22:42
0
56

函数名:is_a()

适用版本:PHP 4, PHP 5, PHP 7

用法:is_a() 函数用于检查一个对象是否属于指定的类或其子类。

语法:bool is_a( object $object, string $class_name )

参数:

  • $object:要检查的对象。

  • $class_name:要检查的类名。

返回值:

  • 如果 $object 是 $class_name 的一个对象或者 $class_name 的一个子类的对象,则返回 true。

  • 如果 $object 不是 $class_name 的一个对象或者 $class_name 的一个子类的对象,则返回 false。

示例:

class Person {
    public $name;
}

class Student extends Person {
    public $grade;
}

$person = new Person();
$student = new Student();

// 检查 $person 是否是 Person 类的对象
if (is_a($person, 'Person')) {
    echo '$person 是 Person 类的对象';
} else {
    echo '$person 不是 Person 类的对象';
}

// 检查 $student 是否是 Person 类的对象
if (is_a($student, 'Person')) {
    echo '$student 是 Person 类的对象';
} else {
    echo '$student 不是 Person 类的对象';
}

// 检查 $student 是否是 Student 类的对象
if (is_a($student, 'Student')) {
    echo '$student 是 Student 类的对象';
} else {
    echo '$student 不是 Student 类的对象';
}

输出:

$person 是 Person 类的对象
$student 是 Person 类的对象
$student 是 Student 类的对象

以上示例中,我们定义了一个 Person 类和一个 Student 类,Student 类是 Person 类的子类。我们创建了一个 $person 对象和一个 $student 对象。使用 is_a() 函数来检查这些对象的类属关系。第一个检查表明 $person 是 Person 类的对象,第二个检查表明 $student 也是 Person 类的对象,第三个检查表明 $student 是 Student 类的对象。

评论
一个月内的热帖推荐
啊龙
Lv.1普通用户

9545

帖子

31

小组

3242

积分

赞助商广告
站长交流