compact — 変数名とその値から配列を作成する


これは多分、こんな時に役立つ。
class Storage {
  private $stock = array();

  public function store($foods) {
    $this->stock = array_merge($this->stock, $foods);
  }

  public function view() {
    foreach ($this->stock as $type => $foods) {
      echo '%lt;p>' . $type . ':' . implode(', ', $foods) . "</p>\n";
    }
  }
}

$fruits = array(
  'a' => 'apple',
  'b' => 'banana',
  'c' => 'cherry');

$vegetables = array(
  'a' => 'asparagus',
  'b' => 'basil',
  'c' => 'carrot');

$storage = new Storage();
$storage->store(array('fruits' => $fruits));
$storage->store(array('vegetables' => $vegetables));

$storage->view();


■実行結果(イメージ)
fruits: apple, banana, cherry
vegetables: asparagus, basil, carrot


んで、この部分を
$storage->store(array('fruits' => $fruits));
$storage->store(array('vegetables' => $vegetables));

こんな風に置き換えられる。
$storage->store(compact('fruits', 'vegetables'));