Created
July 8, 2012 00:11
-
-
Save RalfAlbert/3068674 to your computer and use it in GitHub Desktop.
Get a class constant from outside of the class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class 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' ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment