Skip to content

Instantly share code, notes, and snippets.

@rolfvreijdenberger
Created March 12, 2013 10:20
Show Gist options
  • Save rolfvreijdenberger/5141792 to your computer and use it in GitHub Desktop.
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.
/**
* 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