PHP:将类常量转储到数组中的最简单方法是什么?


PHP: what is the easiest way to dump class constants into array

我有一个带有常量列表的类。我想要像 get_object_vars 这样的东西将常量转储到数组中。最简单的方法是什么?

提前谢谢你!

这将需要使用反射类:

function getClassConstants($class) {
    $reflection = new ReflectionClass(
        is_object($class) ? get_class($class) : $class
    );
    return $reflection->getConstants();
}
// usage: $constants = getClassConstants('myClass');
//        $constants = getClassConstants($myClassObjectInstance);

或者,您可以通过将其传递到类中$this而不是参数来将其实现为类中的方法

文档

PHP 的反射类 - http://us2.php.net/manual/en/class.reflectionclass.php

PHP 的 ReflectionClass::getConstants -http://us2.php.net/manual/en/reflectionclass.getconstants.php