laravel - 为什么没有括号的函数调用? [英] laravel - why function call with no parentheses?
问题描述
Auth :: user() - > item;
其中item是一个函数,在models \User.php里面:
function item(){return $ this-> hasMany('Item','owner_id'); }
其中Item是模型的\Item.php
那么为什么在调用item函数时不需要括号呢?像: Auth :: user() - > item();
如果我把括号,浏览器变得疯狂和崩溃。 b
$ b
另外,如果我将Item.php重命名为Item2.php,将Item Item重命名为Item2,而且我做了 谢谢, Patrick 这会调用 括号是不需要的,因为 I see this in a laravel tutorial : where item is a function, inside models\User.php : where Item is for models\Item.php So why the parentheses is not needed when item function is called ? Like : Also, if I rename Item.php to Item2.php, rename class Item to Item2, and I do Thanks, Patrick Laravel uses the magic function This calls The parentheses are not needed because 这篇关于laravel - 为什么没有括号的函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! hasMany('Item2','owner_id' code>,这是行不通的。但为什么 ?
Illuminate \Database\Eloquent\Model
的 getAttribute
函数,模型的关系,并返回相关的项目(S),如果与该名称的关系。
getAttribute
项目
时,code>自动执行函数 items()
。您可以顺便请求 Auth :: user() - > item();
这将返回一个您可以使用的查询生成器。 b $ bAuth::user()->item;
function item() { return $this->hasMany('Item', 'owner_id'); }
Auth::user()->item();
If I put the parentheses, the browsers goes crazy and crash.hasMany('Item2', 'owner_id')
, it won't work. But why ? Where does 'Item' came from ?__get
to handle arbitrary attributes.Illuminate\Database\Eloquent\Model
's getAttribute
function, which checks the model's relations and returns the related item(s) if a relationship is present with that name.getAttribute
automatically executes the function items()
when the attribute items
is requested. You can, by the way, request Auth::user()->item();
which will return a query builder you can work with.