Skip to content

Instantly share code, notes, and snippets.

@RalfAlbert
Created July 8, 2012 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RalfAlbert/3068674 to your computer and use it in GitHub Desktop.
Save RalfAlbert/3068674 to your computer and use it in GitHub Desktop.
Get a class constant from outside of the class
<?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