$this->attributes ['email'] 是什么用法?

$this->attributes['email'] 是PHP自己的语法吗?
为什么不直接用 $this->email
求教,谢谢!

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
最佳答案

使用$this->attributes['email'] 或者 $this->email 没有本质上的区别,$this->email 在框架底层还是会调用 $this->attributes['email]

当使用 $user->email时, 因为 User.php 和它所继承的类(父类或者 trait) 中都没有email这个属性,这时候会调用 Model类 的 __get() 这个魔术方法。

file

我们继续追踪

file

通过注释我们知道,他调用了 Model 类的 attributes 属性, 这个属性是通过

file

这个 trait 引入的。

file

这就是 laravel 实现的动态属性

5年前 评论
讨论数量: 5

使用$this->attributes['email'] 或者 $this->email 没有本质上的区别,$this->email 在框架底层还是会调用 $this->attributes['email]

当使用 $user->email时, 因为 User.php 和它所继承的类(父类或者 trait) 中都没有email这个属性,这时候会调用 Model类 的 __get() 这个魔术方法。

file

我们继续追踪

file

通过注释我们知道,他调用了 Model 类的 attributes 属性, 这个属性是通过

file

这个 trait 引入的。

file

这就是 laravel 实现的动态属性

5年前 评论

使用$this->attributes['email'] 或者 $this->email 没有本质上的区别,$this->email 在框架底层还是会调用 $this->attributes['email]

当使用 $user->email时, 因为 User.php 和它所继承的类(父类或者 trait) 中都没有email这个属性,这时候会调用 Model类 的 __get() 这个魔术方法。

file

我们继续追踪

file

通过注释我们知道,他调用了 Model 类的 attributes 属性, 这个属性是通过

file

这个 trait 引入的。

file

这就是 laravel 实现的动态属性

5年前 评论

@theDog 到最后的图为之也只是说明attribute属性是个空数组而已

4年前 评论

@theDog
抱歉,我还不是特别明白。
email这个属性是在User.php
protected $fillable = [ 'name', 'email', 'password', ];
里定义的。
那么,定义以后,email这个属性就会出现在HasAttributesprotected $atrributes这个数组里,是这样理解吗?
然后, 我们用$this->attributes['email']时,发现找不到email,所以调用__get(),一直到array_key_exsits($key, $this->attributes),然后发现HasAttributesprotected $atrributes里有email,也就是找到了,所以把数据取出来。
请问有没有哪里理解不对?
谢谢

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!