According to this article (written by Vance Lucas), you can create a new call scope inside the definition of the Foo class using the "anonymous" function, and then you can call get_object_vars() from the inside. This will allow you to get only public properties inside your class, even if they were created dynamically later from the outside.
So for your example, this would be:
<?php class Foo { private $bar = '123'; protected $boo = '456'; public $beer = 'yum'; // return an array of public properties public function getPublicVars(){ $publicVars = create_function('$obj', 'return get_object_vars($obj);'); return $publicVars($this); } } $foo = new Foo(); $foo->tricky = 'dynamically added var'; $result = $foo->getPublicVars(); print_r($result);
and the output will be:
Array
(
[beer] => yum
[tricky] => dynamically added var
)
In the article mentioned above there is a second example that shows another way to do the same using so-called โclosuresโ (from php 5.3), but for some reason it does not work for me with php v5.4 therefore private and protected properties remain included in the resulting array.
jumc
source share