Home > Mobile >  Using die() to return array?
Using die() to return array?

Time:10-18

Assume the following code...

function helper_function($arg){
   if($arg === NULL){
      // I want this to act like die();
      return ["error" => "the variable is null"];
   }else{
      return ["success!" => $arg];
   }
}

// now, we use our helper function
$another_value = "test";

function my_function($another_value){
   helper_function(NULL);
   helper_function($another_value);
}

now the problem here is that I use helper_function around 10 times in my code, so I can't just be checking for if an error exists in the output of that function every time I call it.

TLDR: my_function() should return the error.

Please let me know if this is unclear. Very big thanks

CodePudding user response:

I am not entirely sure I understand correctly what you want, but based on the comments you provided, I think you are looking for something like this:

function helper_function($arg){
   if($arg === NULL) throw new Exception('the variable is null');
   else{
      return ["success!" => $arg];
   }
}

function my_function($another_value) {
    helper_function($another_value); // first call
    helper_function(null); // second call
    helper_function($another_value); // third call
}

try {
    my_function('test');
} catch (Exception $e) {
    /** one of the helper functions encountered an error do something to recover from this error **/
}

If helper_function throws an exception, you can catch that exception in an outer function also, thus you don't have to check after every helper_function for an error. This way, if my_function encounters an error, it will be reported back to you in the catch block of the code.

You can read more about Exceptions here: https://www.php.net/manual/en/language.exceptions.php

If helper_function can raise different kind of errors, and you want to know the exact error raised, you can modify the functions in the following way:

function helper_function($arg) {
   if ($arg === NULL) throw new Exception('null value received', 100);
   else if ($arg === false) throw new Exception('false value received', 200);
   else return ["success!" => $arg];
}

try {
    my_function($another_value);
} catch (Exception $e) {
    if ($e->getCode() === 100) {
       // a null value was received somewhere, do something about it
    } else if ($e->getMessage() === 'false value received') {
       // a false value was received somewhere, do something about it
    }
}

Basically, you can retrieve the exception message and/or code from the caught exception, thus you can raise different kind of errors, and handle those errors in a way you see fit.

  •  Tags:  
  • php
  • Related