Which way is more correct not to let a function run

Asked

Viewed 30 times

1

Well, I couldn’t find a more specific title for my question, my doubt is simple. I won’t decorate much. Come on.

Which of these two are correct:

Without return false;

public static function select($query, $array)
{
    if (!is_array($array))
    {
        die('Database select: Parameter two is not an array');
    }
}

With return false;

public static function select($query, $array)
{
    if (!is_array($array))
    {
        die('Database select: Parameter two is not an array');
        return false;
    }
}

I would like explanations if anything is incorrect, in my view the second option is unnecessary because the die already makes the application stop isn’t it? or with the return false it’s safer for her not to continue?

2 answers

1


After the die it makes no difference what you will write, simply die "kills" the execution and nothing else will be executed after this (with the exception of functions in register_shutdown_function), namely the return false nor will come back and you will not be able to even catch the answer of ::select.

Being a class I find it quite wrong to use die in case of argument in invalid format, in this specific case (I’m talking about this type of case and not for any "thingy") an Exception would look good, as for example the native PHP Exception:

Example of use:

public static function select($query, $array)
{
    if (!is_array($array))
    {
        throw new InvalidArgumentException('O segundo parametro aceita somente arrays');
    }
}

Note also that since the PHP 5.3 exists for array and class a certain type of typing in function parameters, array in this case would look like this:

public static function select($query, array $array)
{
}

Then you wouldn’t even need Exception.

Note that to capture expcetion will have to use Try/catch, but ai depends, because anyway if you issue an error like this is because there is already something wrong in the use of the class and should not even go to the production server, already in development meets well.

  • 1

    Opa liked the reply, I can not give +1 on account of my rep but thanks man

  • @Banks imagines, what matters is that I was able to help him :)

0

Put the return after one die or exit it makes no difference, since both (die and Exit) will stop the execution of the program, that is, neither will it get to execute the return false;

Remarks:

  • Return false also not sure of anything, depending on the context, false is a possible output and can indicate that the program has successfully terminated, depends on how your application will interpret this return

  • It is also possible to use a shorter syntax: is_array($array) or die("Database select: Parameter two is not an array")

  • Opa thanks man I can not give more 1 on account of my rep but thanks

  • @Banks quiet

Browser other questions tagged

You are not signed in. Login or sign up in order to post.