Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get public properties of a class?

I can't use simply get_class_vars() because I need it to work with PHP version earlier than 5.0.3 (see http://pl.php.net/get_class_vars Changelog)

Alternatively: How can I check if property is public?

like image 767
Kamil Szot Avatar asked Jan 07 '10 15:01

Kamil Szot


3 Answers

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
        )

)
like image 121
Kamil Szot Avatar answered Oct 16 '22 09:10

Kamil Szot


Or you can do this:

$getPublicProperties = create_function('$object', 'return get_object_vars($object);');
var_dump($getPublicProperties($this));
like image 39
ultra Avatar answered Oct 16 '22 08:10

ultra


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    
like image 41
XLars Avatar answered Oct 16 '22 08:10

XLars