CONST를 PHP 클래스에서 정의 할 수 있습니까?
일부 클래스에 여러 개의 CONST가 정의되어 있으며 해당 목록을 얻고 싶습니다. 예를 들면 다음과 같습니다.
class Profile {
const LABEL_FIRST_NAME = "First Name";
const LABEL_LAST_NAME = "Last Name";
const LABEL_COMPANY_NAME = "Company";
}
Profile
클래스에 정의 된 CONST 목록을 얻는 방법이 있습니까? 내가 알 수있는 한 가장 가까운 옵션 ( get_defined_constants()
)은 트릭을 수행하지 않습니다.
실제로 필요한 것은 상수 이름 목록입니다.
array('LABEL_FIRST_NAME',
'LABEL_LAST_NAME',
'LABEL_COMPANY_NAME')
또는:
array('Profile::LABEL_FIRST_NAME',
'Profile::LABEL_LAST_NAME',
'Profile::LABEL_COMPANY_NAME')
또는:
array('Profile::LABEL_FIRST_NAME'=>'First Name',
'Profile::LABEL_LAST_NAME'=>'Last Name',
'Profile::LABEL_COMPANY_NAME'=>'Company')
이것을 위해 Reflection 을 사용할 수 있습니다 . 이 작업을 많이 수행하면 결과 캐싱을보고 싶을 수 있습니다.
<?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());
산출:
Array
(
'LABEL_FIRST_NAME' => 'First Name',
'LABEL_LAST_NAME' => 'Last Name',
'LABEL_COMPANY_NAME' => 'Company'
)
$reflector = new ReflectionClass('Status');
var_dump($reflector->getConstants());
token_get_all ()을 사용하십시오 . 즉:
<?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";
}
?>
산출:
LABEL_FIRST_NAME = "First Name"
LABEL_LAST_NAME = "Last Name"
LABEL_COMPANY_NAME = "Company"
PHP5에서는 Reflection :을 사용할 수 있습니다 (수동 참조)
$class = new ReflectionClass('Profile');
$consts = $class->getConstants();
ReflectionClass (PHP 5)를 사용할 수 있다면 PHP 문서 주석에 따라 :
function GetClassConstants($sClassName) {
$oClass = new ReflectionClass($sClassName);
return $oClass->getConstants();
}
Using ReflectionClass and getConstants()
gives exactly what you want:
<?php
class Cl {
const AAA = 1;
const BBB = 2;
}
$r = new ReflectionClass('Cl');
print_r($r->getConstants());
Output:
Array
(
[AAA] => 1
[BBB] => 2
)
Yeah, you use reflection. Look at the output of
<?
Reflection::export(new ReflectionClass('YourClass'));
?>
That should give you the idea of what you'll be looking at.
It is handy to have a method inside the class to return its own constants.
You can do this way:
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 with static method - to the rescue
Looks like it is a nice place to use Traits with a static function to extend class functionality. Traits will also let us implement this functionality in any other class without rewriting the same code over and over again (stay DRY).
Use our custom 'ConstantExport' Trait with in Profile class. Do it for every class that you need this functionality.
/**
* 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;
}
USE EXAMPLE
// So simple and so clean
$constList = Profile::getConstants();
print_r($constList); // TEST
OUTPUTS:
Array
(
[LABEL_FIRST_NAME] => First Name
[LABEL_LAST_NAME] => Last Name
[LABEL_COMPANY_NAME] => Company
)
Why not put them in a class variable as an array to begin with? Makes it easier to loop thru.
private $_data = array("production"=>0 ...);
Eventually with namespaces:
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_());
참고URL : https://stackoverflow.com/questions/956401/can-i-get-consts-defined-on-a-php-class
'Programing' 카테고리의 다른 글
HTML 형식의 이메일을 보내는 방법은 무엇입니까? (0) | 2020.07.04 |
---|---|
MSBuild를 실행하면 SDKToolsPath를 읽을 수 없습니다. (0) | 2020.07.04 |
UIWebView 내에서 Javascript를 디버깅하는 몇 가지 방법은 무엇입니까? (0) | 2020.07.04 |
큰 HTML 문자열에서 jQuery 객체 만들기 (0) | 2020.07.04 |
AttributeError : 'datetime'모듈에 'strptime'속성이 없습니다. (0) | 2020.07.04 |