略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: ReflectionClass::getParentClass

2024-12-21

ReflectionClass::getParentClass

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getParentClass获取父类

说明

public ReflectionClass::getParentClass(): ReflectionClass

警告

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

一个 ReflectionClass

参见

add a noteadd a note

User Contributed Notes 3 notes

up
13
isaac dot z dot foster at gmail dot com
9 years ago
Quick correction, the code for getting all parent classes below has a "typo", you need to reset the $class variable to the parent class instance, otherwise it just endlessly loops:

        $class = new ReflectionClass('classname');
       
        $parents = array();
       
        while ($parent = $class->getParentClass()) {
            $parents[] = $parent->getName();
            $class = $parent;
        }
       
        echo "Parents: " . implode(", ", $parents);
up
3
havelangep at hotmail dot com
11 years ago
Here is a "replacement" for is_a that will additionally look both into the extended classes and in the implemented interfaces

<?php
/**
     * Check if a class extends or implements a specific class/interface
     * @param string $search The class or interface name to look for
     * @param string $className The class name of the object to compare to
     * @return bool
     */
   
function IsExtendsOrImplements( $search, $className ) {
       
$class = new ReflectionClass( $className );
        if(
false === $class ) {
            return
false;
        }
        do {
           
$name = $class->getName();
            if(
$search == $name ) {
                return
true;
            }
           
$interfaces = $class->getInterfaceNames();
            if(
is_array( $interfaces ) && in_array( $search, $interfaces )) {
                return
true;
            }
           
$class = $class->getParentClass();
        } while(
false !== $class );
        return
false;
    }
?>
up
-9
jochem at drecomm dot nl
11 years ago
When you want to find all parents (parent, parent of parent, parent of parent's parent and so on) try:

<?php
$class
= new ReflectionClass('whatever');

$parents = array();

while (
$parent = $class->getParentClass()) {
   
$parents[] = $parent->getName();
}

echo
"Parents: " . implode(", ", $parents);
?>

ReflectionClass::getParentClass() can return a ReflectionClass object of the parent class or false if no parent.

(PHP Version 5.1.6)

官方地址:https://www.php.net/manual/en/reflectionclass.getparentclass.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3