There is such code:

class test { private $a = 0; protected $b = 0; public $c = 0; public function echoprop() { foreach($this as $key => $val) { echo "$".$key." = ".$val.";\n"; } } } $var = new test; $var->echoprop(); 

If you run it, it will display all the properties of the object, but I would not hurt to know the scope of each property.

PS var_dump not offer var_dump as it displays all the information.

1 answer 1

Try it like this.

 <?php class test { private $a = 0; protected $b = 0; public $c = 0; public function echoprop() { $reflector = new ReflectionClass(get_class($this)); foreach($this as $key => $val) { $prop = $reflector->getProperty($key); if( $prop->isPrivate() ) { echo 'Private'; } else if( $prop->isProtected() ) { echo 'Protected'; } else if( $prop->isPublic() ) { echo 'Public'; } echo "$".$key." = ".$val.";\n"; } } } $var = new test; $var->echoprop(); 

I can also offer such a perverted version :) without ReflectionClass. The PHP function get_class_vars returns an array of class methods that are within the scope of this function.

That is, so you can get all the methods of visibility.

 class test { private $a = 0; protected $b = 0; public $c = 0; public function getVisibleProps() { return get_class_vars(get_class($this)); } } class testExtend extends test { public function getVisibleProps() { return get_class_vars(get_class($this)); } } $var = new test; $allPublicProtectedPrivateProps = $var->getVisibleProps(); $varExtend = new testExtend(); $allPublicProtectedPropers = $varExtend ->getVisibleProps(); $allPublicProps = get_class_vars(get_class($var)); 

Next, you just need to get the allPublicProtectedPrivateProps , allPublicProtectedPropers and $allPublicProps and get the corresponding properties with their scopes.

And here is another solution. But needs parsing.

 class test { public $var1 = 1; protected $var2 = 2; private $var3 = 3; static $var4 = 4; public function toArray() { return (array) $this; } } $t = new test; print_r($t->toArray()); /* outputs: Array ( [var1] => 1 [ * var2] => 2 [ test var3] => 3 ) */ 

By key, you can understand the scope.

But this is too perversely obtained - well, not programmerly, so to speak :)

  • About this class heard =) By the way, but you can not do without him? - MaximPro
  • one
    Plus, here the label will be unnecessarily because you have already given the correct answer, and the meaning of the question doesn’t change the presence of the label ... I missed this revision for now but I don’t think it will be accepted. - Naumov
  • @MaximPro above in response added option without ReflectionClass :) - Daniel Abyan
  • @DanielAbyan Game without ReflectionClass - MaximPro
  • @MaximPro Yeah. Well, I think there will still be interesting solutions - it became interesting to myself: D - Daniel Abyan