[英]About compact method in Laravel
public function index()
{
$code = '123456789';
$color = 'Red';
$cars = ['Ford', 'Oddy', 'Tesla'];
$hobbies = ['cricket', 'volleyball', 'swimming'];
return view('posts', compact('code', 'color', 'cars', 'hobbies'));
}
Why does the compact
method use variable names without the $
sign? 为什么compact
方法使用不带$
符号的变量名?
The compact method pulls in the string name of a preceding variable(s). 紧凑方法提取前面的变量的字符串名称。 That's the design of the basic PHP. 这就是基本PHP的设计。 If you look at the comments on the method itself, it helps describe a bit more: 如果您查看有关方法本身的注释,则它有助于描述更多内容:
Each parameter can be either a string containing the name of the variable, or an array of variable names. 每个参数可以是包含变量名称的字符串,也可以是变量名称数组。 The array can contain other arrays of variable names inside it; 该数组可以在其中包含其他变量名数组。 compact handles it recursively. compact递归地处理它。
One other note, with PHP 7.3, a breaking change was introduced to this method within PHP - if the variable has not been initialized previous to calling compact, it will fail. 另一个注意事项是,在PHP 7.3中,PHP中对该方法进行了重大更改-如果在调用compact之前未初始化变量,则该变量将失败。 This was not the case previous to 7.3, and thus caused a significant amount of refactoring for many developers. 7.3之前不是这种情况,因此对许多开发人员造成了大量的重构。 Beware to initialize your compacted vars if using < 7.3 and plan to upgrade in future. 如果使用<7.3,请注意初始化压缩的var,并计划在将来进行升级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.