Application Error Handler Function

I am relatively new to programming. I am trying to catch and display errors in my application. With a global variable, simply:

$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 without a global variable?

Sorry for my English;)

+4
source share
2 answers

How to make it global, i.e.

<?php
class Name {
  public $errors;

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

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

      return;
  }
}

Then each time you run fucntion in this class, check to see if an error has been generated:

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

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

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);
    }
+1
source

Source: https://habr.com/ru/post/1618247/


All Articles