6

我不能仅仅get_class_vars()因为我需要它与早于 5.0.3 的 PHP 版本一起使用(参见http://pl.php.net/get_class_vars Changelog)

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

4

3 回答 3

8

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

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

)
于 2010-01-07T15:47:13.193 回答
3

或者你可以这样做:

$getPublicProperties = create_function('$object', 'return get_object_vars($object);');
var_dump($getPublicProperties($this));
于 2010-03-03T20:04:34.653 回答
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    
于 2013-11-17T09:46:17.070 回答