我需要使用变量引用一个对象属性,代码如下:
```
object[propertyVariable]
```
对象中$data属性的值是一个JSON数组。现在我的用户类看起来像这样:
上面的代码总是返回'',但是
$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'
。