我有以下内容,但我无法弄清楚如何将$ type变量传递给第二个checkUkPhone函数或弄清楚如何引用它。有什么想法吗?
public function isValidUkPhone($fieldName, $type) {
//Set the filter options
$this -> _filterArgs[$fieldName] = array('filter' => FILTER_CALLBACK, 'options' => array($this, 'checkUkPhone'));
}
public function checkUkPhone($type) {
$this -> _errors[$fieldName] = $FieldName.':Phone must begin with 07';
}
// Apply the validation tests using filter_input_array()
$this->_filtered = filter_var_array($data, $this->_filterArgs);
foreach ($this->_filtered as $key => $value) {
// Skip items that used the isBool() method or that are either missing or not required
if (in_array($key, $this->_booleans) || in_array($key, $this->_missing) || !in_array($key, $this->_required)) {
if (in_array($key, $this->_missing)){
$this->_errors[$key] = $key . ':Required';
}
continue;
} elseif ($value === false) {
// If the filtered value is a boolean false, it failed validation,
// so add it to the $errors array
$this->_errors[$key] = $key . ':Invalid data supplied';
}
}
// Return the validated input as an array
return $this->_filtered;
答案 0 :(得分:1)
假设您使用的是PHP 5.3或更高版本,则可以使用闭包。它稍微复杂一点,因为你想使用魔术变量$this
,但不是太难:
public function isValidUkPhone($fieldName, $type) {
//Set the filter options
$that = $this;
$this->_filterArgs[$fieldName] = array(
'filter' => FILTER_CALLBACK,
'options' => function($val) use($fieldName, $type, $that) {
$that->checkUkPhone($val, $fieldName, $type);
}
);
}
public function checkUkPhone($val, $fieldName, $type) {
switch ($type) {
case 'mobile':
// Mobile numbers are a very rigid format
// Some numbers matched by this technically are special services, but are
// charged at around mobile rates
// In case you're wondering, I come from a telephony background
if (!preg_match('/^07[0-9]{9}$/', $val)) {
$this->_errors[$fieldName] = $fieldName.':Phone must begin with 07 and be 11 digits';
}
break;
case 'geographic':
// There are still a few 10 digit 01 numbers floating about
if (!preg_match('/^(?:01[0-9]{8,9}|0[23][0-9]{9})$/', $val)) {
$this->_errors[$fieldName] = $fieldName.':Phone must begin with 01, 02 or 03';
}
break;
case 'non-geographic':
// Due to some weird exceptions to the rules (e.g. ChildLine), it's not as
// easy as above to write a nice simple validation regex for UK non-geos.
// I'll leave that in your hands...
break;
}
}