出于方便起见,Laravel 允许您以这种方式传递数据,但事实并非如此魔法方法. 魔法方法 http://php.net/manual/en/language.oop5.magic.php是 PHP 类中一组选定方法的名称,通常以双下划线开头__
,各有各的目的。魔术方法的例子有__call http://php.net/manual/en/language.oop5.overloading.php#object.call, __callStatic http://php.net/manual/en/language.oop5.overloading.php#object.callstatic, __toString http://php.net/manual/en/language.oop5.magic.php#object.tostring etc.
Laravel 使用 PHP 魔法方法,特别是__call
魔术方法,提供您正在体验的功能。这__call http://php.net/manual/en/language.oop5.overloading.php#object.call当您尝试调用对象上不存在的方法时,PHP 会调用方法。作为其第一个参数,它接收被调用方法的名称,第二个参数接收作为数组传递给方法调用的参数。
Laravel 通过实现来利用这一点__call
方法上的View
班级。它检查开发人员调用的方法的开头是否以with
如果是这样,它将假定方法名称的以下部分表示渲染视图时要绑定数据的变量的名称:
From 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 (! Str::startsWith($method, 'with')) {
throw new BadMethodCallException("Method [$method] does not exist on view.");
}
return $this->with(Str::camel(substr($method, 4)), $parameters[0]);
}
这提供了您正在体验的功能,并且该技术实际上用在几个不同的地方,例如,在查询构建器/Eloquent 中,您可以通过简单地调用以开头的方法来动态地将 where 子句添加到查询中where
方法调用的其余部分引用您正在检查的列:
User::whereEmail('[email protected] /cdn-cgi/l/email-protection'); // Equal to User::where('email', '[email protected] /cdn-cgi/l/email-protection');