【问题标题】:How to get public properties of a class?如何获取类的公共属性?
【发布时间】:2011-01-02 13:04:16
【问题描述】:

我不能简单地使用get_class_vars(),因为我需要它与早于 5.0.3 的 PHP 版本一起使用(请参阅 http://pl.php.net/get_class_vars 变更日志)

或者:我如何检查财产是否是公开的?

【问题讨论】:

  • 我认为这只会是 PHP 5.0.2 中的问题。在 PHP 5.0.1 和更早的版本中,protected 和 private 属性被返回,但以 nul 字节 (\x00) 为前缀,可以用正则表达式排除。

标签: php class properties public


【解决方案1】:

这可以通过使用反射来实现。

<?php

class Foo {
  public $alpha = 1;
  protected $beta = 2;
  private $gamma = 3;
}

$ref = new ReflectionClass('Foo');
print_r($ref->getProperties(ReflectionProperty::IS_PUBLIC));

结果是:

Array
(
    [0] => ReflectionProperty Object
        (
            [name] => alpha
            [class] => Foo
        )

)

【讨论】:

    【解决方案2】:

    或者你可以这样做:

    $getPublicProperties = create_function('$object', 'return get_object_vars($object);');
    var_dump($getPublicProperties($this));
    

    【讨论】:

      【解决方案3】:

      你可以让你的类实现 IteratorAggregate 接口

      class Test implements IteratorAggregate
      {
          public    PublicVar01 = "Value01";
          public    PublicVar02 = "Value02";
          protected ProtectedVar;
          private   PrivateVar;
      
          public function getIterator()
          {
              return new ArrayIterator($this);
          }
      }
      
      
      $t = new Test()
      foreach ($t as $key => $value)
      {
          echo $key." = ".$value."<br>";
      }
      

      这将输出:

      PublicVar01 = Value01
      PublicVar02 = Value02    
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-07
        • 1970-01-01
        • 2014-03-14
        • 1970-01-01
        • 2010-11-30
        • 2015-08-11
        • 2010-10-23
        • 2011-11-22
        相关资源
        最近更新 更多