1

How to loop through all public variables in a class from inside the class?

How to get the public variables?

private function translate_null_values_to_strings(){
    foreach($this->public_vars as $key => $value){
        if(is_null($this->$key)) $this->$key = '';
    }
}
3

1 Answer 1

3

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

class Test
{
    public $public1 = 'public 1';
    public $public2 = '';
    public $public3 = 'public 3';
    private $private1 = 'private 1';

    public function __construct()
    {
        $reflect = new ReflectionObject($this);
        foreach ($reflect->getProperties(ReflectionProperty::IS_PUBLIC) as $prop)
        {
            $propName = $prop->getName();
            echo $propName." --> ". $this->$propName . "\n";
        }
    }
}

$ob = new Test();

Output:

public1 --> public 1
public2 --> 
public3 --> public 3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.