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

I need a function that give an instance and a dot notation string and return its equivalent object. Something like this

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

How can I do this

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