【问题标题】:How to get the const/ static properties of a PHP class如何获取 PHP 类的 const/ 静态属性
【发布时间】:2019-07-16 12:08:56
【问题描述】:

我正在开发一个 PHP 应用程序。现在,我试图通过反射循环遍历 PHP 类的所有静态/常量属性。

我有这样的课

class MyClass
{
   const MY_CONST = "my_const";
   public static $MY_STATIC_PROP = "my_static_prop";
}

我想要做的是我想遍历一个类的所有属性并检查属性的名称是否等于某物。

if ($property_name == "something") {
    //do something
}

我如何在 PHP 中做到这一点?

【问题讨论】:

标签: php reflection


【解决方案1】:

要获得privatepublic 属性,您可以使用get_object_vars(),对于conststatic 属性可以使用ReflectionClass() 类对象。最后合并所有属性。示例:

class MyClass
{
    const MY_CONST = "my_const";
    public static $MY_STATIC_PROP = "my_static_prop";
    public $pub = 'Pub';
    public $pvt = 'Pvt';
}

$ref = new ReflectionClass('MyClass');

$allProperties = get_object_vars(new MyClass) + $ref->getConstants() + $ref->getStaticProperties();

foreach ($allProperties as $name => $vale) {
    if ($name === 'something') {
        // do stuff
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多