显然存在一些允许这种行为的讨厌的代码,请参阅Illuminate\View\View:
/**
* Dynamically bind parameters to the view.
*
* @param string $method
* @param array $parameters
* @return \Illuminate\View\View
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
if (! Str::startsWith($method, 'with')) {
throw new BadMethodCallException(sprintf(
'Method %s::%s does not exist.', static::class, $method
));
}
return $this->with(Str::camel(substr($method, 4)), $parameters[0]);
}
所以这个__call方法捕获了对视图实例的所有方法调用。调用view()->withTest('abc')将导致$method = 'withTest'并最终级联到仅调用的最后一行$this->with('test', 'abc')。
所以最终结果没有区别。withTest链条看起来很讨厌。
恕我直言,应该避免使用这些魔术方法;要么compact()像你已经做的那样使用表格,或者简单地使用:
view('myview', [
'foo' => 123,
'bar' => 'abc'
]);
// or
view('myview')->with([
'foo' => 123,
'bar' => 'abc'
]);
// or
$foo = 123;
$bar = 'abc';
view('myview', compact('foo', 'bar'));
// or
view('myview')->with(compact('foo', 'bar'));
可悲的是,有多种可能性。