[英]How does Laravel's “withVariableName” works?
Looking at Laravel code I found they are passing variable from 'routes' to 'views' using the following method: 查看Laravel代码,我发现它们正在使用以下方法将变量从“路线”传递到“视图”:
$arraysan = ['mike','robert','john']; **//Variable to be passed**
return view('home')->withArraysan($arraysan); **//Variable passed with** name "withArraysan"
In that above syntax they call a function named withArraysan
which doesn't exist. 在上面的语法中,它们调用了一个不存在的名为
withArraysan
的函数。
Can somebody explain how its been handled in Laravel? 有人可以解释一下如何在Laravel中处理它吗?
For a while now, PHP has had the concept of magic methods
- these are special methods that can be added to a class to intercept method calls that do not exist. 一段时间以来,PHP有了
magic methods
的概念-这些是特殊方法,可以将其添加到类中以拦截不存在的方法调用。
It appears that Laravel Views implement __call
- this then intercepts a call to an undefined method on the object, and is passed both the name of the method being called as well as the arguments. 看来,Laravel浏览器
__call
-这则拦截的对象对一个未定义的方法的调用,并传递这两个方法的名字被称为以及参数。 In this way, the View object can then see that the withArraysan
call began with
and call the concrete method with
, passing the second part Arraysan
as the first argument, and the argument to withArraysan
as the second part. 通过这种方式,视图对象就可以看出,
withArraysan
呼叫开始with
和调用的具体方法with
,通过第二部分Arraysan
作为第一个参数,而参数withArraysan
作为第二部分。
If I've got your question then in Laravel they had a class View
using magic method __call
to handle the above function and the code for that function is like as follows 如果我有您的问题,那么在Laravel中,他们可以使用魔术方法
__call
来处理View
的类,该函数的代码如下所示
public function __call($method, $parameters)
{
if (Str::startsWith($method, 'with')) {
return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
}
throw new BadMethodCallException("Method [$method] does not exist on view.");
}
And you can find this within 你可以在里面找到它
your_project_folder/vendor/laravel/framework/src/Illuminate/View/View.php
$arraysan = ['mike', 'robert', 'john']; // Variable to be passed
return view('home')->with('AnyVariable', $arraysan);
Try this! 尝试这个! This will work.
这将起作用。
Also check in home.blade.php, 还要签入home.blade.php,
<?php
print_r($AnyVariable);die;
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.