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

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

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

使用$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年前 评论

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