Why does the return "end" the script even though it is in a condition?

1

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);

Output: 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);

Output: Início : true : Fim

Doubt

  • Why does return "delete" the rest of script , since it is not contained in if ?
asked by anonymous 06.12.2018 / 17:29

2 answers

3

Because when you return, you are literally leaving the function. In other words, 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% of% checking if the values are negative. If any of them is, we return as 0. If we have something outside the rules of the function, why continue its execution? This if indicates that we will return to the function that called return 0 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's actions. Note this in void functions can be soma() a little more difficult.

    
06.12.2018 / 17:34
1

As you used the if and else conditionals, all possibilities are encompassed, so it will certainly fall into one of the two, so the return will be triggered, this for the execution of the function, as can be seen here .

    
06.12.2018 / 17:34