0

我在 PHP 中有一个类层次结构,并且在一些父类中我定义了一个常量,假设TYPE我的示例调用了该常量。

我希望能够为TYPE我的一个类可能已经定义的一个有效值传递一个有效值,然后取回定义该常量的最古老的父类(我称之为该常量的“源类”。)我有编写了以下代码并且它可以工作,但是感觉很重,我想知道是否有更好,更高效的方法来做到这一点?

<?php

class Foo {
    const TYPE = 'idiom';
}

class Bar extends Foo {}

class Baz extends Bar {}

function get_type_origin_class( $class, $type ) {
  $origin_class = false;
  $ref = new ReflectionClass( $class );
  while ( $ref && $type == $ref->getConstant( 'TYPE' ) ) {
    $origin_class = $ref->getName();
    $ref = $ref->getParentClass();
  }
  return $origin_class;
}

echo get_type_origin_class( 'Baz', 'idiom' ); // Echos: Foo
echo get_type_origin_class( 'Bar', 'idiom' ); // Echos: Foo
echo get_type_origin_class( 'Foo', 'idiom' ); // Echos: Foo
4

0 回答 0