D
D
Daniel2021-02-20 14:51:40
PHP
Daniel, 2021-02-20 14:51:40

How to properly exit a PHP script?

Hello! There is a console application that takes some parameters as input and displays the result. If the parameter is entered incorrectly, then an error is intercepted, a custom message is displayed, and the script ends after die() / exit(), since its further execution does not make sense.

The code is just for example:

class App
    {
        public static function checkEven ($number)
        {
            try {
                if ($number % 2 !== 0) {
                    throw new Exception("Odd number");
                } 
                return $number . ' even' . PHP_EOL;
            } catch (Exception $error) {
                print_r($error->getMessage() . PHP_EOL);
                
                die(); // @codeCoverageIgnore
                print_r("Too late");
            }
        }
    }
    
    print_r(App::checkEven(9));


When testing with UNIT tests with incorrect input data, the application terminates along with the test itself (which is not surprising). Recording // @codeCoverageIgnoredidn't help.

Are there other ways to skip execution, die()or should exceptions be handled differently? If so, how?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Decadal, 2021-02-20
@Decadal

>Are there other ways to skip execution of die() or should exceptions be handled differently? If so, how?
replace die with return and swap it with print_r. You don't really need to forcibly terminate php - as soon as the code is executed, the request processing will complete itself.
If you are afraid that some action will be performed somewhere below the code, which should be performed only in case of successful completion, add an additional condition there that will check the result, or catch the exception there, and leave the catch empty. And all will be well.

N
Northern Lights, 2021-02-20
@php666

https://github.com/nategood/commando

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question