如何获得类的公共属性?

时间:2010-01-07 15:30:43

标签: php class properties public

我不能简单地使用get_class_vars(),因为我需要它使用早于5.0.3的PHP版本(参见http://pl.php.net/get_class_vars Changelog)

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

3 个答案:

答案 0 :(得分:7)

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

<?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
        )

)

答案 1 :(得分:3)

或者你可以这样做:

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

答案 2 :(得分:1)

您可以让您的类实现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