Search code examples
phploopsautoloader

Is it wrong to use the return statement this way?


I've got this autoloader method which is used to include class files as needed.

public static function autoloader($className) {

    $fileExists = false;
    foreach(array(LIBS_PATH, CONTROLLERS_PATH, MODELS_PATH) as $path) {

        // Check if the class file exists and is readable
        if(is_readable($classPath = $path . '/' . $className . '.php')) {
            // Include the file
            require($classPath);
            $fileExists = true;
            break;
        }
    }

    if($fileExists === false) {
        exit('The application cannot continue as it is not able to locate a required class.');
    }
}

That works fine but I was thinking is this way better:

public static function autoloader($className) {

    foreach(array(LIBS_PATH, CONTROLLERS_PATH, MODELS_PATH) as $path) {

        // Check if the class file exists and is readable
        if(is_readable($classPath = $path . '/' . $className . '.php')) {
            // Include the file
            require($classPath);
            return;
        }
    }
    exit('The application cannot continue as it is not able to locate a required class.');
}

As you can see I'm using the return statement in the middle of the loop to terminate the rest of the function because the class file has been included and the method has done its job.

Which way is the best way to break out of the loop if a match has been found? I'm just unsure about using the return statement because I always associated that with returning some value from a method.


Solution

  • Return can be used to simply break out of a method/function, and this use is perfectly legal. The real question to ask is what impact do you feel it has on readability?

    There are different schools of thought on early returns.

    One school maintains a single entry/exit point, stating that it makes the code easier to read since one can be assured that logic at the bottom of the code will be reached.

    Another school states that the first school is outdated, and this is not as pressing a concern, especially if one maintains shorter method/function lengths.

    A medium exists between the two where a trade-off between an early return and convoluted logic is present.

    It comes down to your judgment.