Hin und wieder komme ich in die Verlegenheit außerhalb einer Klasse eine ihrer Konstante verwenden zu wollen oder zu müssen. Auf direkten Weg, also z.B. mit Foo:CONSTANT
geht es nicht. Mit der folgenden Methode geht es jedoch wunderbar:
<?phpclass Foo{ const BAR = 'Hallo'; const BAZ = 'Welt!';
/** * * Returns the value of a class constant * @param string $const Name of the constant * @param string $class [optional] Name of the class (if not set, the constant will be searched in this class) * @return mixed|false The value of the constant or false if it does not exists */ public static function get_constant( $const = '', $class_name = __CLASS__ ){
if( empty( $const ) || ! is_string( $const ) || ! class_exists( $class_name ) ) return FALSE;
$reflection = new ReflectionClass( $class_name );
return $reflection->getConstant( $const );
}
}
class Bar{ const FOO = 'Horst';}
$consts = array( 'BAR', 'BAZ', 'FOO' );foreach( $consts as $const ) var_dump( Foo::get_constant( $const ) );
var_dump( Foo::get_constant( 'FOO', 'Bar' ) );
var_dump( Foo::get_constant( 'TEST', 'Baz' ) );