Use reflection in PHP to get a list of constants

PHP lacks a good way of creating enumerations. The best practice is to create constants and use those as possible values. The downside is that you normaly write them hard coded multiple times.

For example you've got the following status options:

class Person  
{
    const STATUS_PENDING   = "pending"
    const STATUS_ACTIVE    = "active";
    const STATUS_DISABLED  = "disabled";
    const STATUS_DELETED   = "deleted";

    public function getStatusOptions()
    {
        return [
            self::STATUS_PENDING,
            self::STATUS_ACTIVE,
            self::STATUS_DISABLED,
            self::STATUS_DELETED
        ];
    }
}

A nice way of getting a list without hard coding is to use reflection.

public function getStatusOptions()  
{
    $reflector = new ReflectionClass(get_class($this));
    $constants = $reflector->getConstants();
    $values = [];

    foreach($constants as $constant => $value) {
        $prefix = "STATUS_";
        if(strpos($constant, $prefix) !==false) {
            $values[] = $value;
        }
    }

    return $values;
}

Or you can abstract it even further and build a static helper function to use for all classes. When doing so you can also add options to get it as an associative array or to exclude spicific ones from the list1:

/**
 * Return array of constants for a class
 *
 * @param string      $class  Class name
 * @param null|string $prefix Prefix like e.g. "KEY_"
 * @param boolean     $assoc  Return associative array with constant name as key
 * @param array       $exclude Array of excluding values
 *
 * @return array Assoc array of constants
 */
public static function getConstants($class, $prefix = null, $assoc = false, $exclude = [])  
{
    $reflector = new ReflectionClass($class);
    $constants = $reflector->getConstants();
    $values = [];

    foreach($constants as $constant => $value) {
        if(($prefix && strpos($constant, $prefix) !==false) || $prefix === null) {
            if(in_array($value, $exclude)) {
                continue;
            }
            if($assoc) {
                $values[$constant] = $value;
            } else {
                $values[] = $value;
            }
        }
    }

    return $values;
}
comments powered by Disqus