If you want to return the constants defined inside a class then you can also define an internal method as follows:
<?php
class myClass {
const NONE = 0;
const REQUEST = 100;
const AUTH = 101;
// others...
static function getConstants() {
$oClass = new ReflectionClass(__CLASS__);
return $oClass->getConstants();
}
}
?>
PHP.mk документација
ReflectionClass::getConstants
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Патека
reflectionclass.getconstants.php
Локална патека за оваа страница.
Извор
php.net/manual/en
Оригиналниот HTML се реупотребува и локално се стилизира.
Режим
Прокси + превод во позадина
Кодовите, табелите и белешките остануваат читливи во истиот тек.
Референца
reflectionclass.getconstants.php
ReflectionClass::getConstants
Референца за `reflectionclass.getconstants.php` со подобрена типографија и навигација.
ReflectionClass::getConstants
класата mysqli_driver
ReflectionClass::getConstants — Ги добива константите
= NULL
Ги добива сите дефинирани константи од класа, без оглед на нивната видливост.
Параметри
filter-
Изборниот филтер, за филтрирање на посакуваните константи видливост. Се конфигурира со користење на ReflectionClassConstant константи, и стандардно е сите константи видливост.
Вратени вредности
Еден array на константи, каде клучевите го држат името, а вредностите вредноста на константите.
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.0.0 |
filter е додадена.
|
Белешки од корисници 6 белешки
andre dot roesti at 7flex dot net ¶
пред 11 години
Panni ¶
пред 7 години
If you want to define a static getConstants() function which works with inheritance you can do the following:
<?php
abstract class AbstractClass
{
const TEST = "test";
public static function getConstants()
{
// "static::class" here does the magic
$reflectionClass = new ReflectionClass(static::class);
return $reflectionClass->getConstants();
}
}
class ChildClass extends AbstractClass
{
const TYPE_A = 1;
const TYPE_B = 'hello';
}
$example = new ChildClass();
var_dump($example->getConstants());
// Result:
array(3) {
'TYPE_A' => int(1)
'TYPE_B' => string(5) "hello"
'TEST' => string(4) "test"
}
?>
Sandor Toth ¶
пред 9 години
You can pass $this as class for the ReflectionClass. __CLASS__ won't help if you extend the original class, because it is a magic constant based on the file itself.
<?php
class Example {
const TYPE_A = 1;
const TYPE_B = 'hello';
public function getConstants()
{
$reflectionClass = new ReflectionClass($this);
return $reflectionClass->getConstants();
}
}
$example = new Example();
var_dump($example->getConstants());
// Result:
array ( size = 2)
'TYPE_A' => int 1
'TYPE_B' => (string) 'hello'
shgninc at gmail dot com ¶
12 години пред
I use a functions to do somthing base on the class constant name as below. This example maybe helpful for everybody.
<?php
public function renderData($question_type = NULL, $data = array()) {
$types = array();
$qt = new ReflectionClass(questionType);
$types = $qt->getConstants();
if ($type = array_search($question_type, $types)){
//.....Do somthing
}
}
?>
djhob1972 at yahoo dot com dot au ¶
пред 16 години
I was trying to determine how to get a var_dump of constants that are within an interface. Thats right, not using any classes but the interface itself.
Along my travels I found it quite interesting that the ReflectionClass along with a direct call to the interface will also dump its constants. Perfect!!!!
This was using PHP 5.3.1 and my example as below:-
1st File:
constants.php
<?php
<?php>
interface MyConstants
{
// --------------------------
// Programmatic Level
// --------------------------
const DEBUG_MODE_ACTIVE = FALSE;
const PHP_VERSION_REQUIREMENT = "5.1.2";
}
?>
=======
Second file:
=======
test.php
<?php>
include_once ("constants.php");
$oClass = new ReflectionClass ('MyConstants');
$array = $oClass->getConstants ();
var_dump ($array);
unset ($oClass);
?>
what you would get from the command line:-
?:\???\htdocs\????>php test.php
array(2) {
["DEBUG_MODE_ACTIVE"]=> bool(false)
["PHP_VERSION_REQUIREMENT"]=> string(5) "5.1.2"
But as you can see this can work quite well to your advantage in many ways so I truely hope this helps someone else with a similar headache in the future to come!
Enjoy!
dmitrochenkooleg at gmail dot com ¶
пред 6 години
Get the latest constants declared.
abstract class AbstractEnum
{
/**
* Возвращает все константы класса || Return all constants
*
* @return array
*/
static function getConstants()
{
$rc = new \ReflectionClass(get_called_class());
return $rc->getConstants();
}
/**
* Возвращает массив констант определенные в вызываемом классе || Return last constants
*
* @return array
*/
static function lastConstants()
{
$parentConstants = static::getParentConstants();
$allConstants = static::getConstants();
return array_diff($allConstants, $parentConstants);
}
/**
* Возвращает все константы родительских классов || Return parent constants
*
* @return array
*/
static function getParentConstants()
{
$rc = new \ReflectionClass(get_parent_class(static::class));
$consts = $rc->getConstants();
return $consts;
}
}
======
class Roles extends AbstractEnum
{
const ROOT = 'root';
const ADMIN = 'admin';
const USER = 'user';
}
// Output:
All: root, admin, user
Last: root, admin, user
class NewRoles extends Roles
{
const CLIENT = 'client';
const MODERATOR = 'moderator';
const SUPERMODERATOR = 'super'.self::USER;
}
// Output:
All: client, moderator, superuser, root, admin, user
Last: client, moderator, superuser
class AdditionalRoles extends Roles
{
const VIEWER = 'viewer';
const CHECKER = 'checker';
const ROOT = 'rooter';
}
All: viewer, checker, rooter, client, moderator, superuser, admin, user
Last: viewer, checker, rooter