PHP クラスで定義された CONST を取得できますか? 質問する

PHP クラスで定義された CONST を取得できますか? 質問する

いくつかのクラスに複数の CONST が定義されており、それらのリストを取得したいと考えています。例:

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

クラスで定義されている CONST のリストを取得する方法はありますかProfile? 私の知る限り、最も近いオプション ( 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')

ベストアンサー1

使用できます反射このためです。これを頻繁に行う場合は、結果をキャッシュすることを検討してください。

<?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'
)

おすすめ記事