Search code examples
phpmethodsternary

Using PHP ternary operators to pass data to a method


I've been working on some custom classes including a debug bug method. Using a constant debug variable

define('DEBUG', 3);

I set what level of debug I want to display. From FALSE (none), 1 (basic), 2 (medium), 3 (advanced), etc etc.

Throughout the code I have calls to said debug method. Exp:

if(DEBUG == TRUE)
    $this->status("DB connection",NULL);

Can this be condensed into a ternary operator? something like:

$this->debug($title, $response, $die) = (DEBUG == TRUE) ? ("DB Connection", NULL) : (NULL) ;

I know its a bit longer but having it all on one line etc would make it easier to maintain.


Solution

  • You should do it the other way around. Make a debug method/function, which you call with a debug level, always, without condition. Inside that method, decide whether the level is met.

    $this->debug('DB connection', DEBUG_INFO);
    
    public function debug($message, $level) {
        if (DEBUG >= $level) {
            echo $message;
        }
    }