0
\$\begingroup\$
    public function setErrorReporting() {
    if($this->debugMode == 0) {
        error_reporting(0);
    } elseif($this->debugMode == 1) {
        error_reporting("E_ALL");
    } elseif($this->debugMode == 2) {
        error_reporting("E_ALL");
        // Also log errors
    }

I want to change the error reporting based on a value from a config file. (eithor 0, 1 or 2) But if I ever wanted to increase the options then it won't scale like this.

Is there a better way of handling this?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Instead of setting the error_reporting based in your code, why not switch php.ini files, based on environment variables? \$\endgroup\$ Commented Nov 20, 2014 at 16:23

1 Answer 1

1
\$\begingroup\$

I would make the function take an optional argument. This argument $mode could be your user defined logging level that would skip the normal logic to determine the reporting level.

An example could be:

public function set_error_reporting($mode = null) {

    $reporting = null;

    if(!is_null($mode)) {

        $reporting = $mode;

    }else{

        switch($this->debug_mode) {

            case 0:
                $reporting = 0;
                break;

            case 1:
                $reporting = E_ALL;
                break;

            case 2:
                $reporting = E_ALL;
                ini_set('log_errors', 1);  // Enable error logging
                break;

            default:
                $reporting = null;
                break;

        }
    }

    // Check if no reporting level was selected

    if(is_null($reporting)) {
        // throw exception (preferred) or emit an error.
    }

    error_reporting($reporting);
}

Then to set the error reporting level automatically.

$obj->set_error_reporting();

Or if you would like to specify another reporting level from a config file.

$level = E_ALL & ~E_NOTICE;  // Log all errors except notices.

$obj->set_error_reporting($level);

This will require you to fetch the reporting level configuration from outside the function. You could also add more case statements to the switch if you know they will be used beforehand.

Let me know if you have any questions or there is something you would like to point out.

Best regards.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.