考虑下面的代码:处理缺阵偏移
$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