开发者

How to get public properties of a class?

开发者 https://www.devze.com 2022-12-15 22:01 出处:网络
I can\'t use simply get_class_vars() because I need it to work with PHP version e开发者_如何学Goarlier than 5.0.3 (see http://pl.php.net/get_class_vars Changelog)

I can't use simply get_class_vars() because I need it to work with PHP version e开发者_如何学Goarlier than 5.0.3 (see http://pl.php.net/get_class_vars Changelog)

Alternatively: How can I check if property is public?


This is possible by using reflection.

<?php

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

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

the result is:

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

)


Or you can do this:

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


You can make your class implement the IteratorAggregate interface

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>";
}

This will output:

PublicVar01 = Value01
PublicVar02 = Value02    
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号