考慮下面的代碼:處理缺陣偏移
$tests = array(
array ("a", "b", "c"), array ("1", "2", "3"), array ("!", "@")
);
foreach ($tests as $test)
test($test[0], $test[1], $test[2]);
function test($param1, $param2, $param3) {
// do whatever
}
這將沒有任何問題的工作,直到它到達$測試[2],這當然沒有在第三個元素陣列,這將導致PHP吐出:
Notice: Undefined offset: 2
有沒有辦法來解決這個問題,除了:它得到一個笨拙
foreach ($tests as $test) {
if (count($x) == 2)
test($test[0], $test[1]);
else
test($test[0], $test[1], $test[2]);
}
function test($param1, $param2, $param3=null) {
// do whatever
}
每個$ test數組的大小都變得越來越大。 或者我應該忽略通知?
編輯:這就是我真正想要做:
// wanted this:
function validate() {
$pass = true;
$rules = array (array ('field1', '!=', 'banana'),
array('field2', 'notempty')
);
for ($i=0; $i<count($rules) && $pass; $i++)
$pass = check($rules[$i][0], $rules[$i][1], $rules[$i][1]);
return $pass;
}
function check($field, $operator, $expected) {
$value = $this->getValue($field);
switch ($operator) {
case '!=':
$pass = ($value != $expected);
break;
case '==':
$pass = ($value == $expected);
break;
case 'empty':
$pass = empty($value);
break;
default:
$pass = !empty($value);
break;
}
return $pass;
}
//instead of
function validate() {
$pass = true;
for ($i=0; $i<count($rules) && $pass; $i++)
$pass = check($rules[$i]);
return $pass;
}
function check($check) {
$value = $this->getValue($check[0]);
switch ($check[1]) {
case '!=':
$pass = ($value != $check[2]);
break;
case '==':
$pass = ($value == $check[2]);
break;
case 'empty':
$pass = empty($value);
break;
default:
$pass = !empty($value);
break;
}
return $pass;
}
基本上文體上。
函數的必需參數應該是必需的,或者是完全可選的。爲什麼test()必須採用可變數量的參數?你有沒有嘗試過像傳遞一個單獨的參數作爲一個數組,像'test($ arr)',其中'$ arr'就像'Array('arg1','arg2','arg3_if_present')',那裏有必要的工作?只是看起來需要重構。 – 2010-07-01 16:34:23