0

私は次のものを持っていますが、$ type変数を2番目の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;
4

1 に答える 1

1

PHP 5.3 以降を使用していると仮定すると、クロージャを使用できます。マジック variable を使用する必要があるため、少し複雑になります$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;
  }
}
于 2012-07-16T21:01:10.423 に答える