我试图从php5中的类中获取数据,其中类中的数据是私有的,调用函数正在请求类中的一段数据。我希望能够在不使用case语句的情况下从私有变量中获取特定的数据。从类动态选取变量
我想要做的东西的影响:
public function get_data($field)
{
return $this->(variable with name passed in $field, i.e. name);
}
我试图从php5中的类中获取数据,其中类中的数据是私有的,调用函数正在请求类中的一段数据。我希望能够在不使用case语句的情况下从私有变量中获取特定的数据。从类动态选取变量
我想要做的东西的影响:
public function get_data($field)
{
return $this->(variable with name passed in $field, i.e. name);
}
你可以只使用
class Muffin
{
private $_colour = 'red';
public function get_data($field)
{
return $this->$field;
}
}
然后,你可以这样做:
$a = new Muffin();
var_dump($a->get_data('_colour'));
<?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;
?>
我会小心这类代码,因为它可能允许暴露类的内部数据太多。
谢谢。我也会研究__get。 – JustJon 2010-01-31 02:49:31
很酷。谢谢。不知道那会起作用。 – JustJon 2010-01-31 02:49:14