Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function 为什么函数调用没有括号?_Function_Laravel_Foreign Key Relationship_Parentheses - Fatal编程技术网

Function 为什么函数调用没有括号?

Function 为什么函数调用没有括号?,function,laravel,foreign-key-relationship,parentheses,Function,Laravel,Foreign Key Relationship,Parentheses,我在laravel教程中看到了这一点: Auth::user()->item; 其中item是函数,在models\User.php中: function item() { return $this->hasMany('Item', 'owner_id'); } 其中Item为models\Item.php 那么为什么调用item函数时不需要括号呢?比如:Auth::user()->item() 如果我加上括号,浏览器就会疯狂崩溃 另外,如果我将Item.php重命名为Item2

我在laravel教程中看到了这一点:

Auth::user()->item;
其中item是函数,在models\User.php中:

function item() { return $this->hasMany('Item', 'owner_id'); }
其中Item为models\Item.php

那么为什么调用item函数时不需要括号呢?比如:
Auth::user()->item()
如果我加上括号,浏览器就会疯狂崩溃

另外,如果我将Item.php重命名为Item2.php,将类Item重命名为Item2,并且我确实
hasMany('Item2','owner_id')
,那么它将不起作用。但是为什么呢?“项目”来自哪里

谢谢


Patrick

Laravel使用魔法函数
\uu get
处理任意属性

这将调用
illighted\Database\Eloquent\Model
getAttribute
函数,该函数检查模型的关系,如果存在与该名称的关系,则返回相关项


不需要括号,因为当请求属性
items
时,
getAttribute
会自动执行函数
items()
。顺便说一下,您可以请求
Auth::user()->item()
将返回一个您可以使用的查询生成器。

方法
item()
正在为有口才的ORM设置一个关系,以了解如何准备查询。调用
->item
就是通过它告诉Eloquent您想要该项,然后Eloquent将使用该方法。只有与兼容时,才能直接调用该方法。您给出的示例应该能起到任何作用,但我可能缺少一些内容。

您能给我们提供
Auth::user()->item
的上下文吗?我的初步结论是,某个地方需要函数的引用;公共函数itemszo(){return$this->hasMany('Item','owner_id');}我的应用程序中没有任何“itemszo”。@trogne当您请求属性
itemszo
时,它会执行确实存在的函数
itemszo()
。该函数与同样存在的
模型创建了一个关系。那么,为什么如果我执行Auth::user()->getAuthPassword,而没有final(),它就不会执行getAuthPassword()函数呢?@trogne,因为它不是那样编码的。
getAttribute
函数专门查找关系。所有这些的来源都是免费提供的——所以我建议你去那里寻找进一步的答案。谢谢你,ceejayoz!我知道,Laravel在查找属性的同时,也在使用相同的名称执行函数。此函数将返回类型为“Lightning\Database\Eloquent\Relations\HasMany”的大对象。通过询问属性,我得到了hasMany的具体用途:一个“lightlight\Database\elount\Collection”对象。