从类中动态选择变量

时间:2010-01-31 02:28:41

标签: php class variables this

我正在尝试从php5中的类中获取数据,其中类中的数据是私有的,并且调用函数正在从类中请求一段数据。我希望能够在不使用case语句的情况下从私有变量中获取特定的数据。

我想做点什么:

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

2 个答案:

答案 0 :(得分:1)

你可以使用

class Muffin
{
   private $_colour = 'red';

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

然后你可以这样做:

$a = new Muffin();

var_dump($a->get_data('_colour'));

答案 1 :(得分:0)

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

您可能也希望查看神奇的__get()函数,例如:

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

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

我会小心使用这种代码,因为它可能会暴露出太多的类内部数据。

相关问题