我需要一个给出实例和点符号字符串并返回其等效对象的函数。像这样的东西
public function convert($instance , $str) {
//If $str = 'instance' return $instance
//If $str = 'instance.name' return $instance->name
//If $str = 'instance.member.id' return $instance->member->id
//...
}
我该怎么做
答案 0 :(得分:0)
class sth
{
public function convert($instance , $str)
{
$params = explode('.', $str);
if($params == 1) {
return $instance;
} else {
$obj = $instance;
foreach($params as $key => $param) {
if(!$key) {
continue;
}
$obj = $obj->{$param};
}
}
return $obj;
}
}
$obj = new stdClass();
$obj->test = new stdClass();
$obj->test->test2 = new stdClass();
$sth = new sth();
var_dump($sth->convert($obj, 'sth.test.test2'));