在函数php之外传递变量

时间:2011-07-09 14:28:00

标签: php function

我有一个检查表单验证的函数。如果有错误,则有一个名为$ error的变量。除了函数内部之外,如何在此函数和本页的其余部分之外完成它,知道是否设置了$ error?

我不希望它继续转移到另一页。我知道有全局但因为我在一个函数中启动$ error我猜它在其他函数中不可用。

有什么想法吗?

4 个答案:

答案 0 :(得分:2)

如果您想通过superglobal $GLOBALS array PHP Manual设置和使用全局变量:

$GLOBALS['error'] = value;

该阵列随处可用。所以要小心。

答案 1 :(得分:2)

我会这样做 function validate($form, &$errors)
{
// some code that sets the erros variable
return false;
}

由于$ erros是通过引用传递的,因此该函数可以设置它的值。但是变量本身仍然在调用代码的范围内。

答案 2 :(得分:1)

我有一个表单类,其中包含一个记录错误的静态变量。例如:

<?php
class form {
  //this is our array to hold fields that have errored so we can apply an error class to the input fields
  static public $errors = array();
  static public function setError($error) {
    self::$errors[] = $error;
  }
  static public function parseErrors() {
    $output .= '<ul>';
    foreach(self::$errors as $message) {
      $output .= '<li>'.$message.'</li>';
    }
    $output .= '</ul>';
    return $output;
  }
  //... other functions
}
?>

然后,要从验证功能中记录错误,您可以执行以下操作:

<?php
function myvalidate($value) {
  // if this validation fails
  form::setError('Field is required');
}
?>

然后只需调用parseErrors来吐出错误。请注意,这些只是片段。我实际上有一个与表单类交互的记录器类,将其更改为一些以进行整合。

我更喜欢做这样的事情,而不是使用GLOBALS,使用GLOBALS或SESSION就可以快速搞乱,这是另一种选择。

答案 3 :(得分:0)

我宁愿返回它,并检查它的count()(我通常把错误放在数组中)。如果是> 0然后有错误,否则没有。