应用程序中的错误处理程序函数


Error handler function in application

我在编程方面相对较新。我正在努力捕捉并显示应用程序中的错误。全局变量很简单:

$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>';
    }
}

但我读到你不应该使用全局变量。如果没有全局变量,我怎么能做同样的事情?

对不起我的英语;)

不如不将其全局化,即:

<?php
class Name {
  public $errors;
  /*
  * Validate form
  */
  public function validate_form() {
      (...)
      if ( empty($_POST["blabla"]) ) {
          $this->errors = 'Error';
      }
      (...)
      return;
  }
}

然后,每次在该类中运行函数时,都要检查是否生成了错误:

$obj = new Name()->validate_form();
if(isset($obj->errors)){
  //oops, an error occured, do something
}

您可以抛出异常

<?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);
    }