David Barker
David Barker

Reputation: 14620

Return data from anonymous class variables

I'm looking for a way to achieve the results below. I'm constricted to using this class and it's methods to achieve it.

final class Trade {

    private $users_id;
    private $adj_id;

    public function display() {
        var_dump($this);    
    }

    public function setData($form_results) {
        foreach ($form_results as $var => $value) {
            $this->{$var} = $value;
        }
    }

    public function getData() {
        return get_object_vars($this);
    }
}

The problem is calling get_object_vars() inside the class method. As expected it ignores the private variables I have set and returns an array of all the class variables both public and private due to its scope.

I'm trying to have the method return just the public anonymous variables. Is there a way I can do this?

Upvotes: 0

Views: 104

Answers (2)

a sad dude
a sad dude

Reputation: 2825

Why not just save all the data to some private variable and return that?

If your object must have the data as it's properties, you can use __get and __set to read and set items in that array, and on outside it will look as though they were properties.

Upvotes: 0

Uladzimir Pasvistselik
Uladzimir Pasvistselik

Reputation: 3921

Try to use

   foreach($this as $key => $value) {
       print "$key => $value\n";
   }

See details on http://www.php.net/manual/en/language.oop5.iterations.php

Upvotes: 2

Related Questions