So I want to make a function to display errors instead of saying echo "error message", I want something like $this->errorDisplay('error message');
I currently have this, but it's not doing the job.
function errorDisplay($msg) {
$this->errors[] = $msg;
foreach($this->errors as $error) {
echo $error;
}
}
public function checkFields($username,$password) {
if(!empty($username) && !empty($password)) {
//proceed to validation
} else {
$this->errorDisplay('All fields are required.');
}
}
Jacob
79k24 gold badges159 silver badges245 bronze badges
-
3Your function is doing two things at once: collecting messages, and outputting previously collected ones. Split it up if that's what you actually want to do.mario– mario2015年09月18日 23:36:47 +00:00Commented Sep 18, 2015 at 23:36
-
What exactly is it that you want to happen?Ben Kolya Mansley– Ben Kolya Mansley2015年09月18日 23:37:11 +00:00Commented Sep 18, 2015 at 23:37
-
Why are you putting all the errors in an array if you just want to display one error?Barmar– Barmar2015年09月18日 23:44:15 +00:00Commented Sep 18, 2015 at 23:44
-
Move it around to where? Please rewrite the question and get very clear about what you expect the result to be when you call this multiple times. Where are all the errors supposed to be displayed?Barmar– Barmar2015年09月18日 23:45:59 +00:00Commented Sep 18, 2015 at 23:45
-
1@Zsw My guess is he has taken what he wants and dissappeared.RiggsFolly– RiggsFolly2015年09月19日 01:23:20 +00:00Commented Sep 19, 2015 at 1:23
1 Answer 1
Instead of trying to do everything in one method, split the process into 2. One method adds messages to an array, and the other shows all the previously saved up messages.
Class xxx
{
public $errors = array();
public function addError($msg) {
$this->errors[] = $msg;
}
public function showErrors() {
foreach($this->errors as $error) {
echo $error;
}
}
public function initErrors() {
$this->errors = array();
}
public function checkFields($username,$password) {
$this->initErrors();
if( empty($username) ) {
$this-addError('Username missing');
}
if ( empty($password) ) {
$this-addError('Password missing');
}
if ( count($this->errors) > 0 ) {
$this->showErrors();
}
}
} //end class
answered Sep 19, 2015 at 0:28
RiggsFolly
94.7k22 gold badges108 silver badges152 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-php