Why does Return "terminate" the script even if in a condition?

Asked

Viewed 96 times

2

Example scenario

Example 1

$var = 'A';

function testar($v)
{
    echo 'Início';    
    
    if ($v == 'A') {
    
        echo ' : true';
        return true;
        
    } else {
        
        echo ' : false';
        return false;
    }
    
    echo ' : Fim';
}

testar($var);

Exit: Início : true

Example 2

$var = 'A';

function testar($v)
{
    echo 'Início';    
    
    if ($v == 'A') {
    
        echo ' : true';
        
    } else {
        
        echo ' : false';    
    }
    
    echo ' : Fim';
}

testar($var);

Exit: Início : true : Fim


Doubt

  • Why the return "eliminates" the rest of the script, since it is not contained in if?
  • Because when you use a Return it returns the function result.

  • When you use the Return is to indicate that that is the expected result of the function, then finding this result, it will return the value of the function and end the function.

  • https://answall.com/q/115335/101 e https://answall.com/q/331155/101

2 answers

3


Because when you do Return, you are literally leaving the function. Rather, you are "returning" to the function that called it. When the function returns something, it makes more sense. Imagine the following function:

int soma(int a, int b)
{
    if (a < 0 || b < 0)
        return 0;

    return a + b;
}

This function only adds positive values, for example. So, we have the first if which checks if the values are negative. If any of them are, we return as 0. If we have something outside the rules of the function, why continue its execution? That one return 0 indicates that we will return to the function you called soma() the value of 0. And when this happens, it is because the rest of the function is not important for this case.

Briefly: you returned a result and do not need the rest of the function actions. Note this in void functions can be realmente a little harder.

2

As used the if and Else conditionals, all possibilities are encompassed, then for sure will fall in the in one of the two, so the Return will be triggered, this for the execution of the function, as can be seen here.

  • Your answer is correct and good, it says about what happened. If you detail it more can still be very good.

  • Sorry for the ignorance, but as this could be more detailed?

Browser other questions tagged

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