PHP: working with functions storing array
I have a
function displayErr(){
$err[] = "You have an error";
}
later in my code
if($bla==false) { displayErr(); }
if(!empty($err)) { echo print_r($err); }
I don't get anything, can't I call a function that adds on 开发者_Go百科$err
and then check it later?
The variable $err
is is only visible within the function displayErr()
. What you want is to access a global variable within the function. To do this, you need to import it using the global
keyword, as the following example shows:
function displayErr(){
global $err;
$err[] = "You have an error";
}
For more information regarding variable scope, see this link: http://php.net/manual/en/language.variables.scope.php
$err
is only visible in the scope of your displayErr()
function. You need to pass it, or its values, around. A couple of options:
Return the error message and append to
$err
within the calling scopefunction displayErr() { return "You have an error"; } $err = array(); if($bla==false) { $err[] = displayErr(); } if(!empty($err)) { print_r($err); }
Use
global
function displayErr() { global $err; $err[] = "You have an error"; } $err = array(); if($bla==false) { displayErr(); } if(!empty($err)) { print_r($err); }
Also, print_r()
outputs stuff by itself, you don't need to echo print_r()
.
You can use the global
keyword to store your variable as global:
function displayErr()
{
global $err;
$err = "You have an error";
}
[...]
global $err;
if($bla==false) { displayErr(); } if(!empty($err)) { echo print_r($err); }
$err
is only available in your displayErr
function.
You need to add a global
statement. Like this: displayErr() {global $err; ... }
This is called variable scoping, and you can read more about it here.
A simple error handling class example:
class ErrorHandler()
{
private $errors = array();
public function add_error($error = 'You have an error')
{
$this->errors[] = $error;
}
public function get_errors()
{
return $this->errors;
}
public function print_errors()
{
print_r($this->errors);
}
}
$errorhandler = new ErrorHandler;
if($bla==false) $errorhandler->add_error('Variable bla is not set!');
if($bla=='unknown error') $errorhandler->add_error();
$errors = $errorhandler->get_errors();
if($errors) print_r($errors); // or
if($errors) $errorhandler->print_errors();
精彩评论