2010-07-24 66 views
1

這是一件小事,但它一直在困擾着我。我已經挫敗了我的大腦,以便寫出類似這樣的陳述,而不需要任何重複的代碼。例如:測試和回聲沒有重複?

echo isset($array[0])? $array[0]: 'not set'; 
$var = empty($other_var)? '$other_var not set': $other_var; 

是否有某種測試和回報(爲前),或檢查並設置(後者)操作我不知道?這可能看起來像一個小問題,但重複似乎沒有必要,可能會導致非常長的線條,從而使維護複雜化。考慮:

$another_var = array_key_exists($array[Utility::FindIndex($username)][Constants::App_CRITERION], $haystack[NthDimension('my dimensional indicator')])? $array[Utility::FindIndex($username)][Constants::App_CRITERION], $haystack[NthDimension('my dimensional indicator')]: 'not set'; 

是的,是的,上面的這一行完全是人爲設計的,但不可想象會發生類似的情況。對我來說,看起來很奇怪,沒有辦法測試某些東西,並且在沒有重複的情況下分配它的值(如果是真的話)而沒有重複。

+2

這是微不足道的創建自己的效用函數爲你做那不是嗎? (實際上isset文檔頁面包括其他人的功能,在評論中:http://php.net/manual/en/function.isset.php) – 2010-07-24 21:24:20

+0

你的第二個代碼對我沒有意義:'$ array [ Utility :: FindIndex($ username)] [Constants :: App_CRITERION],$ haystack [NthDimension('my dimensional indicator')]'這應該是什麼? (我指的是'?'子句中的部分,而不是'array_key_exists'。 – NikiC 2010-07-24 22:00:12

回答

2

我認爲在PHP 6中有一個計劃功能叫issetor或類似的東西。但我不記得這個名字。而PHP 6已經死了。

所以,把它寫自己:

function issetor(&$var, $default) { 
    return isset($var) ? $var : $default; 
} 

echo issetor($_GET['me'], 'you'); 

如果你想讓它更抽象的,看看這個:

function isor(&$var, $default, $condition) { 
    if (!is_callable($condition)) { 
     throw new InvalidArgumentExpression('condition not callable!'); 
    } 

    return $condition($var) ? $var : $default; 
} 

// this is equivalent to issetor($_GET['me'], 'you'); 
echo isor($_GET['me'], 'you', function(&$var) { return isset($var); }); 

// but you may use a more complicated thing here, too: 
echo isor($_GET['me'], 'you', function($var) use($allowed) { return in_array($var, $allowed); }); 
// this is equivalent to: 
echo in_array($_GET['me'], $allowed) ? $_GET['me'] : 'you'; 
// now the "normal" version is still shorter. But using isor allows you to store often used $condition closures in variables. For example, if you want to check if several values are in an array, you could write: 
$isAllowed = function ($var) use ($allowed) { 
    return in_array($var, $allowed); 
}; 
$a = isor($a, 'default', $inAllowed); 
$b = isor($b, 'default', $inAllowed); 
$c = isor($c, 'default', $inAllowed); 
$d = isor($d, 'default', $inAllowed); 

如果你想傳遞額外的變量來你的病情功能,無需總是關閉你可能會添加另一個參數。 (請注意,我沒有使用參數數組並call_user_func_array,因爲你可能不使用它每引用傳遞,但顯然它確實是這樣,所以你可以擴展的代碼。)

function isor(&$var, $default, $condition, $addArgument = null) { 
    if (!is_callable($condition)) { 
     throw new InvalidArgumentExpression('condition not callable!'); 
    } 

    return $condition($var, $addArgument) ? $var : $default; 
} 

// the above in_array condition: 
echo isor($a, 'default', 'in_array', $allowed); 
2

它不會處理isset ()的情況下,這是這種模式的主要用例,但PHP 5.3 確實對三元運算符有簡短的形式。

$new_val = $if_true ? $if_true : $if_false; 

可縮短至

$new_val = $if_true ?: $if_false; 

我找不到它的文檔,奇怪的是,但這裏有一個關於它的問題:What is ?: in PHP 5.3?

+2

請參閱http://svn.php.net/viewvc?view=revision&revision=246551 – VolkerK 2010-07-24 22:54:29