简体   繁体   中英

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?

The compact method pulls in the string name of a preceding variable(s). That's the design of the basic 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.

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. This was not the case previous to 7.3, and thus caused a significant amount of refactoring for many developers. Beware to initialize your compacted vars if using < 7.3 and plan to upgrade in future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM