[Solved] Can we return a String in a PHP function? [closed]


They are both equivalent in terms of functionality.

The 2nd form requires an extra temporary variable. That is a micro-optimization that should not be important to you but it does exist.

The concern with Method1 is that you have multiple places where the function can exit/return, and an omission or modification has a greater chance of causing a regression that you might not find if you don’t have good unit test coverage or just plain regression testing.

It also allows you to return entirely different things, which can be convoluted and hard to understand for people who have to modify the code at a later time.

Frequently there are functions that have additional conditions (if-then-elseif etc) where things are not as clear cut, and for that reason, form 2 is sometimes favored. That usually looks a bit different, because it is dependent on setting a default initialization value:

function test() {
    $text="Default value";

    if (some condition)
        $text="Some Text";
    } elseif (some other condition) {
        $text="Some Other Text";
    }
    return $text;
}

1

solved Can we return a String in a PHP function? [closed]