我不能用简单get_class_vars(),因为我需要它与早期版本的PHP的工作比5.0.3(见 http://pl.php.net/get_class_vars 更新日志)

另外:我如何检查是否属性是公共

有帮助吗?

解决方案

这可以通过使用反射。

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

)

其他提示

或者你可以这样做:

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

您可以让你的类实现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    
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top