Created
March 12, 2013 10:20
-
-
Save rolfvreijdenberger/5141792 to your computer and use it in GitHub Desktop.
php snippet to easily get a list of constant key/values from a class. easy in a util class for reuse.
This file contains hidden or 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
/** | |
* gets the constants from a class. this is useful if the constants are part | |
* of a logical group (especially when prefixed with the same value) | |
* @param string $from the classname (can be __CLASS__) | |
* @param string $prefix the prefix for the constants | |
* @param string $values_only do we want a key=>value array or values only | |
* @return array | |
*/ | |
public static function getConstants($from, $prefix = null, $values_only = false) | |
{ | |
$reflection = new ReflectionClass($from); | |
$constants = $reflection->getConstants(); | |
//filter constants on prefix if necessary | |
if($prefix !== null) { | |
$filtered = array(); | |
foreach($constants as $key => $value) | |
{ | |
if( substr($key,0 ,strlen($prefix)) === $prefix){ | |
$filtered[$key] = $value; | |
} | |
} | |
//swap | |
$constants = $filtered; | |
} | |
if($values_only) { | |
$constants = array_values($constants); | |
} | |
return $constants; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment