简体   繁体   English

Laravel中with()和compact()有什么区别

[英]What's the difference between with() and compact() in Laravel

What's the difference between the functions with() and compact() in Laravel in these two examples: 在这两个示例中,Laravel中的with()compact()函数之间有什么区别:

Example 1: 范例1:

return View::make('books.index')->with('booksList', $booksList);

Example 2: 范例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. 好吧, compact()是一个PHP函数 ,它将一个变量列表转换为一个关联数组,其中键是变量名,值是该变量的实际值。

The actual question should be: What is the difference between 实际的问题应该是:两者之间有什么区别

return View::make('books.index')->with('booksList', $booksList);

and

return View::make('books.index', array('booksList' => $booksList));

The answer there isn't really one. 答案实际上不是一个。 They both add items to the view data. 它们都将项目添加到视图数据。

Syntax-wise, View::make() only accepts an array while with() takes both, two strings: 在语法上, View::make()仅接受一个数组,而with()同时接受两个字符串:

with('booksList', $booksList);

Or an array that can possibly hold multiple variables: 或可能包含多个变量的数组:

with(array('booksList' => $booksList, 'foo' => $bar));

This also means that compact() can be used with with() as well: 这也意味着compact()也可以与with()一起with()

return View::make('books.index')->with(compact($booksList));

The compact method passes array data to Constructor which is stored to $data Class attribute : compact方法将数组数据传递给Constructor,并存储到$data Class属性中:

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;
    }

While with() method accepts an array or a string, and in case it is an array it performs array_merge on the parameter otherwise it appends the data to a key which you passed as a paramter to $data attribute, so if you use constructor you're forced to pass an array , while with() accepts a single key with a value. with()方法接受一个数组或一个字符串时,如果它是一个数组,它将对参数执行array_merge,否则它将数据附加到作为参数传递给$data属性的键上,因此,如果使用构造函数,被强制传递一个array ,而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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM