Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 什么';Laravel中with()和compact()的区别是什么_Php_Laravel_Laravel 4 - Fatal编程技术网

Php 什么';Laravel中with()和compact()的区别是什么

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

在这两个示例中,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);
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;
    }
Well
compact()
是一种将变量列表转换为关联数组的方法,其中键是变量名,值是该变量的实际值

实际问题应该是:两者之间的区别是什么

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

谢谢,非常详细。详细信息