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

How to convert dot notation to object in php?

我需要一个函数来提供一个实例和一个点符号字符串以及 return 它的等效对象。像这样

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

我该怎么做

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