Reputation: 488
So I would like to output the properties that are public only from within an 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>';
}
}
I've got this working by using an external function to cycle through an instance of the class but I want to know how to do this from inside. Is there a way to get the access modifier?
example of retrieving public properties externally
$obj = new MyClass();
foreach($obj as $key=$val)
echo $key . ' : ' . $val;
Upvotes: 4
Views: 401
Reputation: 36964
There are different 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 from php 7 you get another behavior.
Upvotes: 3