Pregunta

Tengo varios de CONST definido en algunas clases, y desea obtener una lista de ellos. Por ejemplo:

class Profile {
    const LABEL_FIRST_NAME = "First Name";
    const LABEL_LAST_NAME = "Last Name";
    const LABEL_COMPANY_NAME = "Company";
}

¿Hay alguna manera de obtener una lista de las Constituciones de la clase definida en el Profile? Por lo que yo puedo decir, la opción más cercana (get_defined_constants()) no va a hacer el truco.

Lo que realmente necesito es una lista de los nombres de constantes - algo como esto:

array('LABEL_FIRST_NAME',
    'LABEL_LAST_NAME',
    'LABEL_COMPANY_NAME')

O:

array('Profile::LABEL_FIRST_NAME', 
    'Profile::LABEL_LAST_NAME',
    'Profile::LABEL_COMPANY_NAME')

O incluso:

array('Profile::LABEL_FIRST_NAME'=>'First Name', 
    'Profile::LABEL_LAST_NAME'=>'Last Name',
    'Profile::LABEL_COMPANY_NAME'=>'Company')
¿Fue útil?

Solución

Puede utilizar Reflexión para esto. Tenga en cuenta que si usted está haciendo esto mucho es posible que desee buscar en el almacenamiento en caché el resultado.

<?php
class Profile {
    const LABEL_FIRST_NAME = "First Name";
    const LABEL_LAST_NAME = "Last Name";
    const LABEL_COMPANY_NAME = "Company";
}


$refl = new ReflectionClass('Profile');
print_r($refl->getConstants());

Salida:

Array
(
    'LABEL_FIRST_NAME' => 'First Name',
    'LABEL_LAST_NAME' => 'Last Name',
    'LABEL_COMPANY_NAME' => 'Company'
)

Otros consejos

Este

 $reflector = new ReflectionClass('Status');
 var_dump($reflector->getConstants());

token_get_all () . A saber:

<?php
header('Content-Type: text/plain');

$file = file_get_contents('Profile.php');
$tokens = token_get_all($file);

$const = false;
$name = '';
$constants = array();
foreach ($tokens as $token) {
    if (is_array($token)) {
        if ($token[0] != T_WHITESPACE) {
            if ($token[0] == T_CONST && $token[1] == 'const') {
                $const = true;
                $name = '';
            } else if ($token[0] == T_STRING && $const) {
                $const = false;
                $name = $token[1];
            } else if ($token[0] == T_CONSTANT_ENCAPSED_STRING && $name) {
                $constants[$name] = $token[1];
                $name = '';
            }
        }
    } else if ($token != '=') {
        $const = false;
        $name = '';
    }
}

foreach ($constants as $constant => $value) {
    echo "$constant = $value\n";
}
?>

Salida:

LABEL_FIRST_NAME = "First Name"
LABEL_LAST_NAME = "Last Name"
LABEL_COMPANY_NAME = "Company"

En PHP5 puede utilizar Reflexión: (Manual de referencia)

$class = new ReflectionClass('Profile');
$consts = $class->getConstants();

Por la documentación de PHP comentarios, si usted es capaz de utilizar el ReflectionClass (PHP 5):

function GetClassConstants($sClassName) {
    $oClass = new ReflectionClass($sClassName);
    return $oClass->getConstants();
}

Fuente está aquí.

El uso de ReflectionClass y getConstants() da exactamente lo que quiere:

<?php
class Cl {
    const AAA = 1;
    const BBB = 2;
}
$r = new ReflectionClass('Cl');
print_r($r->getConstants());

Salida:

Array
(
    [AAA] => 1
    [BBB] => 2
)

Sí, utiliza reflexión . Mira la salida de

<?
Reflection::export(new ReflectionClass('YourClass'));
?>

Eso te dará la idea de lo que se busca en.

Es útil tener un método dentro de la clase para volver a sus propias constantes.
Puede hacerlo de esta manera:

class Profile {
    const LABEL_FIRST_NAME = "First Name";
    const LABEL_LAST_NAME = "Last Name";
    const LABEL_COMPANY_NAME = "Company";


    public static function getAllConsts() {
        return (new ReflectionClass(get_class()))->getConstants();
    }
}

// test
print_r(Profile::getAllConsts());

Trait con método estático - al rescate

Parece que es un buen lugar para utilizar rasgos con una función estática para ampliar la funcionalidad de clase. Rasgos también le permitirá a implementar esta funcionalidad en cualquier otra clase sin tener que reescribir el mismo código una y otra vez (no mojarse).

Utilice nuestra costumbre Rasgo 'ConstantExport' con perfil en clase. Hacerlo para cada clase que necesita esta funcionalidad.

/**
 * ConstantExport Trait implements getConstants() method which allows 
 * to return class constant as an assosiative array
 */
Trait ConstantExport 
{
    /**
     * @return [const_name => 'value', ...]
     */
    static function getConstants(){
        $refl = new \ReflectionClass(__CLASS__);
        return $refl->getConstants();
    }
}

Class Profile 
{
    const LABEL_FIRST_NAME = "First Name";
    const LABEL_LAST_NAME = "Last Name";
    const LABEL_COMPANY_NAME = "Company";

    use ConstantExport;

}

Ejemplo de uso

// So simple and so clean
$constList = Profile::getConstants(); 

print_r($constList); // TEST

SALIDAS:

Array
(
    [LABEL_FIRST_NAME] => First Name
    [LABEL_LAST_NAME] => Last Name
    [LABEL_COMPANY_NAME] => Company
)

¿Por qué no los pusieron en una variable de clase como una matriz para empezar? Hace que sea más fácil a través del bucle.

private $_data = array("production"=>0 ...);

Finalmente, con espacios de nombres:

namespaces enums;
class enumCountries 
{
  const CountryAustria          = 1 ;
  const CountrySweden           = 24;
  const CountryUnitedKingdom    = 25;
}

namespace Helpers;
class Helpers
{
  static function getCountries()
  {
    $c = new \ReflectionClass('\enums\enumCountries');
    return $c->getConstants();
  }
}

print_r(\Helpers\Helpers::getCountries());
Class Qwerty 
{
    const __COOKIE_LANG_NAME__ = "zxc";
    const __UPDATE_COOKIE__ = 30000;

    // [1]
    public function getConstants_(){

        return ['__COOKIE_LANG_NAME__' => self::__COOKIE_LANG_NAME__, 
                '__UPDATE_COOKIE__' => self::__UPDATE_COOKIE__]; 
    }    

    // [2]
    static function getConstantsStatic_(){

        return ['__COOKIE_LANG_NAME__' => self::__COOKIE_LANG_NAME__, 
                '__UPDATE_COOKIE__' => self::__UPDATE_COOKIE__]; 
    } 
}

// [1]
$objC = new Qwerty();
var_dump($objC->getConstants_());

// [2]
var_dump(Qwerty::getConstantsStatic_());
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top