使用变量引用对象属性

3
我需要使用变量引用一个对象属性,代码如下: ``` object[propertyVariable] ```
$user = User::find( 1 );
$mobile = $user->getData( 'phone.mobile' );

对象中$data属性的值是一个JSON数组。现在我的用户类看起来像这样:
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'
1个回答

2

Laravel实际上有一个内置的辅助函数,用于您正在尝试执行的确切操作,称为array_get:

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

更多信息请参阅文档:https://laravel.com/docs/5.5/helpers#method-array-get


谢谢您的帮助,如果您能发布一个完成此任务的函数答案,那就太好了。我想看看它是如何完成的。 - Tales

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接