laravel - 为什么没有括号的函数调用? [英] laravel - why function call with no parentheses?

查看:242
本文介绍了laravel - 为什么没有括号的函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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,而且我做了 hasMany('Item2','owner_id' code>,这是行不通的。但为什么 ?

谢谢,

Patrick

解决方案

$ b

这会调用 Illuminate \Database\Eloquent\Model getAttribute 函数,模型的关系,并返回相关的项目(S),如果与该名称的关系。

括号是不需要的,因为 getAttribute

请求属性项目时,code>自动执行函数 items()。您可以顺便请求 Auth :: user() - > item(); 这将返回一个您可以使用的查询生成器。 b $ b

I see this in a laravel tutorial :

Auth::user()->item;

where item is a function, inside models\User.php :

function item() { return $this->hasMany('Item', 'owner_id'); }

where Item is for models\Item.php

So why the parentheses is not needed when item function is called ? Like : Auth::user()->item(); If I put the parentheses, the browsers goes crazy and crash.

Also, if I rename Item.php to Item2.php, rename class Item to Item2, and I do hasMany('Item2', 'owner_id'), it won't work. But why ? Where does 'Item' came from ?

Thanks,

Patrick

解决方案

Laravel uses the magic function __get to handle arbitrary attributes.

This calls 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.

The parentheses are not needed because 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.

这篇关于laravel - 为什么没有括号的函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆