![](/img/trans.png)
[英]How can I access class constants using `self::` inside an anonymous function defined in a method?
[英]Access Self Class Constants
如何在該類內部定義的函數中訪問類常量?
class Test{
const STATUS_ENABLED = 'Enabled';
const STATUS_DISABLED = 'Disabled';
public function someMethod(){
//how can I access ALL the constants here let's say in a form of array
}
}
我並不是要訪問每個常量,而是要以數組形式訪問所有常量。 我看到了類似的東西:
<?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());
但是,如果我想訪問該類內部的所有常量列表怎么辦?
要獲得一個類的所有已定義常量的列表,您需要使用Reflection:
如果要將所有常量收集為數組,則可以使用Reflection :
$reflection = new ReflectionClass("classNameGoesHere");
$reflection->getConstants();
但是,這將非常緩慢並且幾乎沒有意義。 更好的主意是簡單地在另一個數組中聲明所有常量,然后使用:
class Test{
const STATUS_ENABLED = 'Enabled';
const STATUS_DISABLED = 'Disabled';
$states = array(
self::STATUS_ENABLED,
self::STATUS_DISABLED,
}
這樣做的另一個好處是,如果添加更多常量,它將繼續工作。 除非您通過將關系定義為數組來明確地做到這一點,否則沒有理由假定所有類的常量都以任何方式關聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.