實(shí)例
創(chuàng)建一個(gè)包含變量名和它們的值的數(shù)組:
<?php
$firstname = "Bill";
$lastname = "Gates";
$age = "60";
$result = `compact("firstname", "lastname", "age")`;
print_r($result);
Array
(
[firstname] => Bill
[lastname] => Gates
[age] => 60
)
定義和用法
compact() 函數(shù)創(chuàng)建包含變量名和它們的值的數(shù)組。
注釋:任何沒有變量名與之對應(yīng)的字符串都被略過纠亚。
語法
compact(var1,var2...)
參數(shù) | 描述 |
---|---|
var1 | 必需赘阀。可以是帶有變量名的字符串扑眉,或者是變量數(shù)組纸泄。 |
var2,... | 可選赖钞。可以是帶有變量名的字符串刃滓,或者是變量數(shù)組仁烹。允許多個(gè)參數(shù)。 |
說明
compact() 函數(shù)創(chuàng)建一個(gè)由參數(shù)所帶變量組成的數(shù)組咧虎。如果參數(shù)中存在數(shù)組卓缰,該數(shù)組中變量的值也會被獲取。
本函數(shù)返回的數(shù)組是一個(gè)關(guān)聯(lián)數(shù)組砰诵,鍵名為函數(shù)的參數(shù)征唬,鍵值為參數(shù)中變量的值。
本函數(shù)執(zhí)行的行為與 extract() 正好相反茁彭。
應(yīng)用場景
用于框架中給模板分配變量多個(gè)變量
例如yii2中总寒,向視圖中
public function actionCreate()
{
$model = new Category();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
$id = Yii::$app->request->get('id');
// 不用 compact() 函數(shù)
return $this->render('update', [
'model' => $model,
'id' => $id,
]);
// 用 compact() 函數(shù),提高代碼的簡潔性
return $this->render('create', compact('model', 'id'));
}