0

I have a class hierarchy in PHP and in some of the parent classes I have defined a constant, let's assume that constant is called TYPE for my example.

I want to be able to pass in a valid value for TYPE that one of my classes may have defined and then get back the eldest most parent class that defined the constant (what I'm calling 'origin class' for that constant.) I have written the following code and it works, but it feels heavy and I was wondering if there was a better, more performant way to do this?

<?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
BenMorel
  • 34,448
  • 50
  • 182
  • 322
MikeSchinkel
  • 4,947
  • 4
  • 38
  • 46

0 Answers0