5

I'm sure I could find this on PHP.net if only I knew what to search for!

Basically I'm trying to loop through all public variables from within a class.

To simplify things:

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

Should just display Fred's name and email....

2 Answers 2

7

Use Reflection. I've modified an example from the PHP manual to get what you want:

class Person { public $name = 'Fred'; public $email = '[email protected]'; 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"; } } } 
Sign up to request clarification or add additional context in comments.

4 Comments

Cool, I haven't heared of this before. +1. However, have you any knowledge of the performance of this class compared to something like get_class_vars?
Why googling, when the answer is already on SO: stackoverflow.com/questions/294582/…
Ah thanks, not heard of it either - although, like Boldewyn, I'm a little worried about the performance issues!
Reflection is a little slower but if it's got the functionality you need you should go for it regardless. It's not going to be much of an overhead, and it's a very powerful instrument.
0

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

You can use get_class_vars() function:

<?php class Person { public $name = 'Fred'; public $email = '[email protected]'; private $password = 'sexylady'; public function __construct() { $params = get_class_vars(__CLASS__); foreach ($params AS $key=>$val) { echo "$key is $val \n"; } } } ?> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.