Is it recommended to use loose return in a PHP file? When?

8

It's good practice to give a return in a simple PHP file example:

<?php

$config['teste'] = 123;

return $config;

I will explain better this file di / dependencias.php:

<?php


$container['daoExemplo'] = function ($c)
{
    return new ExemploDAO();
};

return $container;

I need to add all the anonymous functions contained in this file in a method, in case it will go through the entire directory di / example:

public function requireAllDependencies($directory)
{
    try {
        //setando o diretorio e o tipo de arquivo a ser carregado
        $dir = "{$directory}/*.php";

        //Percorrendo o diretorio e pegado o caminho dos aquivo
        foreach (glob($dir) as $filename)
        {
            //Adicionando as dependencias
            $dependencies = require $filename;
            $this->add($dependencies);
        }
    } catch(Exception $e) {
        echo "Erro ao tentar adicionar o arquivo: " . $e->getMessage();
    }
}

In this example would it make sense?

    
asked by anonymous 16.01.2018 / 15:13

1 answer

13

In some cases this makes sense. Forget this good practice question, do not use it if you do not know exactly what you are doing.

php handbook explains well how return works when used outside of functions, be it in the main file or includes (different behaviors):

  

If called in global scope , the running script is terminated.

     

If the current script file is included or required with the functions include or require , the control is passed back to the script it is calling. Also, if the current script was included with the include function, the value entered at return will be returned as the value of the include call.

According to this information, your usage example is valid.

    
16.01.2018 / 15:21