0

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.');
    }
}
9
  • 3
    Your 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. Commented Sep 18, 2015 at 23:36
  • What exactly is it that you want to happen? Commented Sep 18, 2015 at 23:37
  • Why are you putting all the errors in an array if you just want to display one error? Commented 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? Commented Sep 18, 2015 at 23:45
  • 1
    @Zsw My guess is he has taken what he wants and dissappeared. Commented Sep 19, 2015 at 1:23

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.