Php 什么';Laravel中with()和compact()的区别是什么
在这两个示例中,Laravel中的函数Php 什么';Laravel中with()和compact()的区别是什么,php,laravel,laravel-4,Php,Laravel,Laravel 4,在这两个示例中,Laravel中的函数with()和compact()有什么区别: 示例1: return View::make('books.index')->with('booksList', $booksList); return View::make('books.index',compact('booksList')); 示例2: return View::make('books.index')->with('booksList', $booksList); retu
with()
和compact()
有什么区别:
示例1:
return View::make('books.index')->with('booksList', $booksList);
return View::make('books.index',compact('booksList'));
示例2:
return View::make('books.index')->with('booksList', $booksList);
return View::make('books.index',compact('booksList'));
compact方法将数组数据传递给构造函数,该构造函数存储到
$data
类属性:
public function __construct(Factory $factory, EngineInterface $engine, $view, $path, $data = array())
{
$this->view = $view;
$this->path = $path;
$this->engine = $engine;
$this->factory = $factory;
$this->data = $data instanceof Arrayable ? $data->toArray() : (array) $data;
}
而with()
方法接受数组或字符串,如果是数组,它会对参数执行数组合并,否则它会将数据附加到作为参数传递给$data
属性的键,因此如果使用构造函数,则必须传递数组,而with()
接受带有值的单个键
public function with($key, $value = null)
{
if (is_array($key))
{
$this->data = array_merge($this->data, $key);
}
else
{
$this->data[$key] = $value;
}
return $this;
}
Wellcompact()
是一种将变量列表转换为关联数组的方法,其中键是变量名,值是该变量的实际值
实际问题应该是:两者之间的区别是什么
return View::make('books.index')->with('booksList', $booksList);
及
答案其实并不存在。它们都将项目添加到视图数据中
语法方面,View::make()
只接受数组,而with()
同时接受两个字符串:
with('booksList', $booksList);
或可能包含多个变量的数组:
with(array('booksList' => $booksList, 'foo' => $bar));
这也意味着compact()
也可以与with()
一起使用:
return View::make('books.index')->with(compact($booksList));
谢谢,非常详细。详细信息