How to filter properties using an access modifier

So, I would like to infer properties that are publicly available only within the class.

class MyClass
{
    $public $var1, $var2, var3;
    $private $pVar1, $pVar2, pVar3;

    //outputs all variables and their values
    //lets assume they are all defined
    function outputPublic()
    {
        foreach($this as $key=>$val)
            echo $key . ' : ' . $val . '<br>';
    }
}

This works for me, using an external function to loop through the class instance, but I want to know how to do this from the inside. Is there a way to get an access modifier?

public property retrieval example

$obj = new MyClass();
foreach($obj as $key=$val)
    echo $key . ' : ' . $val;
+4
source share
1 answer

There is another way. You can use get_object_vars

foreach(call_user_func('get_object_vars', $this) as $key => $val) {
    echo $key . ' : ' . $val . '<br>';
}

or you can use ReflectionClass

$reflect = new ReflectionClass($this);
foreach($reflect->getProperties(ReflectionProperty::IS_PUBLIC) as $props) {
    echo $props->getName() . ' : ' . $props->getValue($this) . '<br>';
}

I recommend using ReflectionClass instead of get_object_vars, which with php 7 gets a different behavior.

+3
source

All Articles