如何在php中将点符号转换为对象?

时间:2015-01-19 10:25:59

标签: php object

我需要一个给出实例和点符号字符串并返回其等效对象的函数。像这样的东西

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
    //...
}

我该怎么做

1 个答案:

答案 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'));