views:

18

answers:

2

I'm trying to get data from a class in php5, where the data in the class is private and the calling function is requesting a piece of data from the class. I want to be able to gain that specific piece of data from the private variables without using a case statement.

I want to do something to the effect of:

public function get_data($field)
{
    return $this->(variable with name passed in $field, i.e. name);
}
A: 

You could just use

class Muffin
{
   private $_colour = 'red';

   public function get_data($field)
   {
      return $this->$field;
   }
}

Then you could do:

$a = new Muffin();

var_dump($a->get_data('_colour'));
robbo
Ah cool. Thanks. Didn't know that would work.
JustJon
A: 
<?php
public function get_data($field)
{
    return $this->{$field};
}
?>

You may want to look at the magical __get() function too, e.g.:

<?php
class Foo
{
        private $prop = 'bar';
        public function __get($key)
        {
                return $this->{$key};
        }
}

$foo = new Foo();
echo $foo->prop;
?>

I would be careful with this kind of code, as it may allow too much of the class's internal data to be exposed.

konforce
Thanks. I'll look into __get as well.
JustJon