Shirtz
Shirtz

Reputation: 68

Error handler function in application

I'm relatively new in programming. I'm trying to catch and display errors in my aplication. With global variable is simple:

$errors = '';

class Name {

    /**
     * Validate form
     */
    public function validate_form() {
    global $errors;

        (...)
        if ( empty($_POST["blabla"]) ) {
            $errors = 'Error';
        }
        (...)

        return;
    }

    /**
     * Display errors
     */
    public function show_error() {
        global $errors;
        if(!empty($errors)) return '<div class="error">' . PHP_EOL . htmlspecialchars($errors) .'</div>';
    }

}

...but i read that you should not use global variables. How can i do the same thing without global variable?

Sorry for my english ;)

Upvotes: 4

Views: 63

Answers (2)

Nelson Owalo
Nelson Owalo

Reputation: 2414

How about not making it global, ie:

<?php
class Name {
  public $errors;

  /*
  * Validate form
  */
  public function validate_form() {

      (...)
      if ( empty($_POST["blabla"]) ) {
          $this->errors = 'Error';
      }
      (...)

      return;
  }
}

Then everytime you run a fucntion in that class, check if an error was generated:

$obj = new Name()->validate_form();

if(isset($obj->errors)){
  //oops, an error occured, do something
}

Upvotes: 1

Halayem Anis
Halayem Anis

Reputation: 7805

You can throw Exceptions

<?php 
class Name {

    /**
     * Validate form
     */
    public function validate_form() {


        (...)
        if ( empty($_POST["blabla"]) ) {
            throw new RuntimeException( 'Error' );
        }
        (...)

        return;
    }
    $obj = new Name();
    /**
     * Display errors
     */
    public function show_error($e) {
        return '<div class="error">' . PHP_EOL . htmlspecialchars($e->getMessage()) .'</div>';
    }
}
 // TEST
    try {    
        $obj->validate_form();
    }
    catch(Exception $e) {
        $obj->show_error($e);
    }

Upvotes: 1

Related Questions