Which way is more correct not to let a function

1

Well, I could not find a more specific title for my question, my question is simple. I'm not going to decorate much. Come on.

Which of these two are correct:

No 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 any is incorrect, in my point of view the second option is unnecessary because die already makes the application stop is not it? or with return false is it safer for it not to continue?

    
asked by anonymous 22.07.2018 / 21:46

2 answers

1

After the die it makes no difference what you are going to write, simply die "kills" the execution and nothing else will be executed after this (except for functions in register_shutdown_function ), ie return false nor will get to return and you will not even get the answer from ::select .

Being a class I find it 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 "little thing") an exception would fall well, such as the exception native PHP:

Example usage:

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

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

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

Then you would not even need the exception.

Note that in order to catch expcetion you will have to use try / catch, but it depends, because if you issue an error anyway, there is something wrong with using the class and you should not go to the production server, development already serves well.

    
22.07.2018 / 21:52
0

Put the return after a die or exit does not make a difference, since both (die and exit) will stop the execution of the program, that is, neither will get to execute the return false;

Comments:

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

    / li>
  • You can also use shorter syntax: is_array($array) or die("Database select: Parameter two is not an array")

22.07.2018 / 21:57