Laravel中with()和compact()有什么区别 [英] What's the difference between with() and compact() in Laravel
问题描述
在这两个示例中,Laravel中的功能with()
和compact()
有什么区别:
What's the difference between the functions with()
and compact()
in Laravel in these two examples:
示例1:
return View::make('books.index')->with('booksList', $booksList);
示例2:
return View::make('books.index',compact('booksList'));
推荐答案
Well compact()
is a PHP function that converts a list of variables into an associative array where the key is the variable name and the value the actual value of that variable.
实际的问题应该是:两者之间有什么区别
The actual question should be: What is the difference between
return View::make('books.index')->with('booksList', $booksList);
和
return View::make('books.index', array('booksList' => $booksList));
答案实际上不是一个.他们都将项目添加到视图数据中.
The answer there isn't really one. They both add items to the view data.
在语法上,View::make()
仅接受一个数组,而with()
则接受两个字符串:
Syntax-wise, View::make()
only accepts an array while with()
takes both, two strings:
with('booksList', $booksList);
或可能包含多个变量的数组:
Or an array that can possibly hold multiple variables:
with(array('booksList' => $booksList, 'foo' => $bar));
这也意味着compact()
也可以与with()
一起使用:
This also means that compact()
can be used with with()
as well:
return View::make('books.index')->with(compact($booksList));
这篇关于Laravel中with()和compact()有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!