【问题标题】:Php: How to list static fields/properties through reflection?Php:如何通过反射列出静态字段/属性?
【发布时间】:2023-03-26 22:42:01
【问题描述】:

假设我有这个课程:

class Example {    
    public static $FOO = array('id'=>'foo', 'length'=>23, 'height'=>34.2);
    public static $BAR = array('id'=>'bar', 'length'=>22.5, 'height'=>96.223);
}

如何使用反射来获取静态字段列表? (类似数组('$FOO', '$BAR')?)

【问题讨论】:

    标签: php reflection static-members


    【解决方案1】:

    您需要使用 [ReflectionClass][1]。 getProperties() 函数将返回 ReflectionProperty 对象的数组。 ReflectionProperty 对象有一个 isStatic() 方法,它会告诉你属性是否是静态的,还有一个 getName() 方法返回名称。

    示例:

    <?php
    
    class Example {    
        public static $FOO = array('id'=>'foo', 'length'=>23, 'height'=>34.2);
        public static $BAR = array('id'=>'bar', 'length'=>22.5, 'height'=>96.223);
    }
    
    $reflection = new ReflectionClass('Example'); 
    $properties = $reflection->getProperties();
    $static = array();
    
    if ( ! empty($properties) )
      foreach ( $properties as $property )
        if ( $property->isStatic() )
          $static[] = $property->getName();
    
    print_r($static);
    

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 2019-06-10
      • 2010-10-01
      相关资源
      最近更新 更多