【问题标题】:PHP Reflection Class. How to get the values of the properties?PHP 反射类。如何获取属性的值?
【发布时间】:2011-02-14 17:39:57
【问题描述】:

我在 PHP 中使用反射类,但我不知道如何获取反射实例中的属性值。有可能吗?

代码:

<?php

class teste {

    public $name;
    public $age;

}

$t = new teste();
$t->name = 'John';
$t->age = '23';

$api = new ReflectionClass($t);

foreach($api->getProperties() as $propertie)
{
    print $propertie->getName() . "\n";
}

?>

如何在 foreach 循环中获取属性值?

最好的问候,

【问题讨论】:

    标签: php reflection get


    【解决方案1】:

    怎么样

    在你的情况下:

    foreach ($api->getProperties() as $propertie)
    {
        print $propertie->getName() . "\n";
        print $propertie->getValue($t);
    }
    

    顺便说一句,由于您的对象只有公共成员,您也可以iterate it directly

    foreach ($t as $propertie => $value)
    {
        print $propertie . "\n";
        print $value;
    }
    

    或使用get_object_vars 将它们提取到数组中。

    【讨论】:

      【解决方案2】:

      另一种方法是使用getDefaultProperties() 方法,如果您不想实例化该类,例如。

      $api->getDefaultProperties();
      

      这是您的完整示例,简化为您正在寻找的内容...

      class teste {
      
          public $name;
          public $age;
      
      }
      
      $api = new ReflectionClass('teste');
      var_dump($api->getDefaultProperties());
      

      注意:你也可以在 ReflectionClass 中使用命名空间。例如,

      $class = new ReflectionClass('Some\Namespaced\Class');
      var_dump($class->getDefaultProperties());
      

      【讨论】:

        猜你喜欢
        • 2013-01-16
        • 1970-01-01
        • 1970-01-01
        • 2020-12-27
        • 1970-01-01
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        • 2017-01-19
        相关资源
        最近更新 更多