passing variables outside of functions php
I have a function that che开发者_JS百科cks form validation. If there is an error then there is a variable called $error. How do I make it so outside of this function and the rest of this page regardless of inside of a function or not, know that $error is set?
I don't want it to carry over to another page though. I know there is global but since I am initiating the $error in a function I guess it is not available in other functions.
Any ideas?
I would make it this way
function validate($form, &$errors)
{
// some code that sets the erros variable
return false;
}
Since $erros is passed by reference, the function can set it's value. But the variable itself remains in the scope of the calling code.
If you want to set and use a global variable via the superglobal $GLOBALS
array PHP Manual:
$GLOBALS['error'] = value;
That array is available everywhere. So take care.
I have a form class with a static variable inside of it that logs errors. For example:
<?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
}
?>
Then to log errors from within your validation functions, you can do something like this:
<?php
function myvalidate($value) {
// if this validation fails
form::setError('Field is required');
}
?>
Then just call the parseErrors to spit out your errors. Please note these are just snippets. I actually have a logger class that interacts with the form class, changed it up some for consolidation.
I prefer doing things like this than using GLOBALS, it can get messy really quick using GLOBALS or the SESSION for that matter, which is another option.
I'd rather return it, and checks its count() (I usually put errors in array). If it's > 0 then there are errors, otherwise there are no.
精彩评论