phpのextract関数の使い方とか逆のことをするcompact関数とかの解説
phpで使えるextract
とは、ざっくり言うと、配列(連想配列)の1つ1つの要素を変数に変換できる関数のこと。
例えば、以下のようなコードを書くと、連想配列のkeyが変数として扱われ、valueがその変数の値になっている事がわかる。
<?php $hash = [name => 'tarou', age => 20]; extract($hash); var_dump($name, $age); string(5) "tarou" int(20)
公式ページを見てわかるように、extract
には引数にオプションを与える事ができる。
extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] ) : int
第2引数の値を変える事で、「もし変数が衝突(被る)した時にどのような処理をするか」とか「変数名の付け方」などの設定ができる。(でも、使い道ある?)
また、extract
関数の引数には、$_GET
のような信頼性の低い配列を引数にしてはいけない。(何故ダメなのかは、調べ中)
詳しくは、以下の公式ページを参照するのが良い。
extractの反対の働きがあるcompact関数
extract
の反対の働きをする関数としてcompact
関数が用意されている。
<?php $name = 'tarou'; $age = 19; $hash = compact('name', 'age'); var_dump($hash);
phpの場合だとarray_merge
関数もあるし、php5以上からは配列の扱いが楽になったので、わざわざcompact
関数を使う必要がないように感じる。
しかし、compact
関数を使う事で、コードがよりシンプルになると言うのを「Why does PHP compact() use strings instead of actual variables? - Stack Overflow」が教えてくれている。
As far as benefits, I've found compact() to be useful in MVC applications. If you're writing controller code and you need to pass an associative array of variables and their apparent names that you've set in your controller to the view, it shortens something like:
View::make('home')->with(array('products' => $products, 'title' => $title, 'filter' => $filter'));
to
View::make('home')->with(compact('products', 'title', 'filter'));
確かに、下のコードの方がシンプルで分かりやすい。