How do I know if a variable is public or private from a PHP class?

I'm sure I can find this on PHP.net if I knew what to look for!

Basically I am trying to iterate over all public variables from a class.

To simplify:

<?PHP class Person { public $name = 'Fred'; public $email = ' fred@example.com '; private $password = 'sexylady'; public function __construct() { foreach ($this as $key=>$val) { echo "$key is $val \n"; } } } $fred = new Person; 

The name and address of Fred should just be displayed ....

+4
source share
2 answers

Use Reflection . I changed the example from the PHP manual to get what you want:

 class Person { public $name = 'Fred'; public $email = ' fred@example.com '; private $password = 'sexylady'; public function __construct() { $reflect = new ReflectionObject($this); foreach ($reflect->getProperties(ReflectionProperty::IS_PUBLIC) as $prop) { $propName = $prop->getName(); echo $this->$propName . "\n"; } } } 
+6
source

http://php.net/manual/en/function.get-class-vars.php

You can use the get_class_vars () function:

 <?php class Person { public $name = 'Fred'; public $email = ' fred@example.com '; private $password = 'sexylady'; public function __construct() { $params = get_class_vars(__CLASS__); foreach ($params AS $key=>$val) { echo "$key is $val \n"; } } } ?> 
0
source

Source: https://habr.com/ru/post/1300405/


All Articles