I've been trying to use the PHP function get_object_vars(). The description of the function says that...
Gets the accessible non-static properties of the given object according to scope.
Well, sort of. Take this code for example...
class Foo {
private $priv = 1;
protected $prot = 2;
public $pub = 3;
public function showFromWithin() {
echo 'From within: ';
print_r(get_object_vars($this));
echo "<br />\n";
}
public function showFromOutside($obj) {
echo 'From outside: ';
print_r(get_object_vars($obj));
echo "<br />\n";
}
public function showAnother() {
echo 'Another: ';
$o = new Bar();
print_r(get_object_vars($o));
echo "<br />\n";
}
}
class Bar {
public $a;
protected $b;
}
$foo = new Foo();
$faz = new Foo();
$foo->showFromWithin();
$foo->showFromOutside($foo);
$faz->showFromOutside($faz);
$foo->showAnother();Here's the result:
From within: Array ( [priv] => 1 [prot] => 2 [pub] => 3 ) //foo
From outside: Array ( [priv] => 1 [prot] => 2 [pub] => 3 ) //foo
From outside: Array ( [priv] => 1 [prot] => 2 [pub] => 3 ) //faz
Another: Array ( [a] => ) //Bar object
I would have thought that calling from outside the object would result in only the public class variables being listed. Maybe in the second case, where an instance of Foo is looking at itself, it works as expected. But when one instance of Foo looks at a different instance of foo ($foo2), shouldn't the private and protected class variables not show?
I don't get it.
0 Responses to PHP scope and get_object_vars()
Leave a Reply