文字

ReflectionClass::getConstants

(PHP 5)

ReflectionClass::getConstants获取一组常量

说明

public array ReflectionClass::getConstants ( void )

获取一个类中所有已定义的常量。

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

常量的 数组 ,常量名是数组的键,常量的值是数组的值。

参见

  • ReflectionClass::getConstant() - 获取定义过的一个常量

用户评论:

[#1] davide dot renzi at gmail dot com [2014-07-16 11:21:15]

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();
    }
}
?>

[#2] shgninc at gmail dot com [2013-11-20 10:00:52]

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
}
}
?>

[#3] djhob1972 at yahoo dot com dot au [2009-12-16 05:42:48]

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!

上一篇: 下一篇: