PHP で私が気に入っている「トリック」の 1 つは、関数が引数の配列を取り、デフォルト値にフォールバックするなどの状況を処理するときに、配列共用体演算子を使用することです。
たとえば、引数として配列を受け入れ、キー'color'
、'shape'
、および ' size
' が設定されていることを知る必要がある次の関数を考えてみましょう。ただし、ユーザーはこれらがどうなるかを常に知っているとは限らないため、いくつかのデフォルトを提供する必要があります。
最初の試みでは、次のようなことを試すかもしれません:
function get_thing(array $thing)
{
if (!isset($thing['color'])) {
$thing['color'] = 'red';
}
if (!isset($thing['shape'])) {
$thing['shape'] = 'circle';
}
if (!isset($thing['size'])) {
$thing['size'] = 'big';
}
echo "Here you go, one {$thing['size']} {$thing['color']} {$thing['shape']}";
}
ただし、配列ユニオン演算子を使用すると、これをよりクリーンにするための優れた「省略形」になる可能性があります。次の関数を考えてみましょう。最初のものとまったく同じ動作をしますが、より明確です。
function get_thing_2(array $thing)
{
$defaults = array(
'color' => 'red',
'shape' => 'circle',
'size' => 'big',
);
$thing += $defaults;
echo "Here you go, one {$thing['size']} {$thing['color']} {$thing['shape']}";
}
もう 1 つの興味深い点は、無名関数(および PHP 5.3 で導入されたクロージャー) です。たとえば、配列のすべての要素を 2 倍するには、次のようにします。
array_walk($array, function($v) { return $v * 2; });