Php 使用变量引用对象属性

Php 使用变量引用对象属性,php,laravel,class,object,properties,Php,Laravel,Class,Object,Properties,我需要使用如下变量引用对象属性: $user = User::find( 1 ); $mobile = $user->getData( 'phone.mobile' ); class User extends Authenticable { protected $fillable = [ 'email', 'password', 'data', 'token', ]; protected $cas

我需要使用如下变量引用对象属性:

$user = User::find( 1 );
$mobile = $user->getData( 'phone.mobile' );
class User extends Authenticable {

    protected $fillable = [
        'email',
        'password',
        'data',
        'token',
    ];

    protected $casts = [
        'data' => 'array',
    ];

    public function getData( $key = null ){
        if( $key == null ){
            // Return the entire data array if no key given
            return $this->data;
        }
        else{
            $arr_string = 'data';
            $arr_key = explode( '.', $key );
            foreach( $arr_key as $i => $index ){
                $arr_string = $arr_string . "['" . $index . "']";
            }
            if( isset( $this->$arr_string ) ){
                return $this->$arr_string;
            }
        }
        return '';
    }
}
对象中$data属性的值是一个jSON数组。现在,我的用户类如下所示:

$user = User::find( 1 );
$mobile = $user->getData( 'phone.mobile' );
class User extends Authenticable {

    protected $fillable = [
        'email',
        'password',
        'data',
        'token',
    ];

    protected $casts = [
        'data' => 'array',
    ];

    public function getData( $key = null ){
        if( $key == null ){
            // Return the entire data array if no key given
            return $this->data;
        }
        else{
            $arr_string = 'data';
            $arr_key = explode( '.', $key );
            foreach( $arr_key as $i => $index ){
                $arr_string = $arr_string . "['" . $index . "']";
            }
            if( isset( $this->$arr_string ) ){
                return $this->$arr_string;
            }
        }
        return '';
    }
}
上面的代码总是返回“”,但
$this->data['phone']['mobile']
返回存储在数据库中的实际值。
我猜我是以错误的方式引用了该键,有人能告诉我访问该值的正确方式吗?给定字符串
'phone.mobile'

Laravel实际上有一个内置的帮助函数,用于您正试图做的事情,称为array\u get:

  public function getData( $key = null ) 
  {
        if ($key === null) {
            return $this->data;
        }
        return array_get($this->data, $key);
  }

有关更多信息,请参阅文档:

感谢您的帮助,如果您还可以发布一个带有相应功能的答案,那将是一件非常好的事情。我想看看是怎么做的。