Search code examples
phpfunctionmethodsreturncode-standards

Best practice for returning in PHP function/method


I am refactoring an extensive codebase overtime. In the long run we are going to develop the whole system in classes but in the mean time I am using the opportunity to refine my PHP skills and improve some of the legacy code we use across several hundred websites.

I have read conflicting articles over time about how best to return data from a custom function, generally the debate falls into two categories, those concerned about best technical practice and those concerned about ease of reading and presentation.

I am interesting in opinions (with elaboration) on what you consider best practice when returning from a custom PHP function.

I am undecided as to which of the following as a better standard to follow using this basic theoretical function for example;

Approach a.

Populating a return variable and returning it at the end of the function:

<?php
function theoreticalFunction( $var )
{
    $return = '';
    if( $something > $somethingelse ){
       $return = true;
    }else{
       $return = false;
    }
    return $return;
}
?>

Approach b.

Returning at each endpoint:

<?php
function theoreticalFunction( $var )
{
    if( $something > $somethingelse ){
       return true;
    }else{
       return false;
    }
}
?>

A possible duplicate could have been What is the PHP best practice for using functions that return true or false? however this is not limited to simply true or false despite my basic example above.

I have looked through the PSR guidelines but didn't see anything (but I may have missed it so please feel free to point me to PSR with reference :) ).

Extending the original question:

Is the method used to return different depending on the expected/desired output type?

Does this method change depending on the use of procedural or object oriented programming methods? As this question shows, object orientation brings in its own eccentricities to further extend the possible formatting/presentation options Best practices for returns methods in PHP

Please try to be clear in your explanations, I am interested in WHY you choose your preferred method and what, if anything, made you choose it over another method.


Solution

  • There are people arguing for single exit points in functions (only one return at the end), and others that argue for fail/return early. It's simply a matter of opinion and readability/comprehensibility on a case-by-case basis. There is hardly any objective technical answer.

    The reality is that it's simply not something that can be prescribed dogmatically. Some algorithms are better expressed as A and others work better as B.

    In your specific case neither is "best"; your code should be written as:

    return $something > $somethingelse;
    

    That would hopefully serve as example that there's simply no such thing as a generally applicable rule.