Following on from this other question.
In the PSR-1 Guidelines, the section 2.3 Side Effects rule restricts using include
and declaring functions in the same file, e.g.:
<?php
// side effect: loads a file
include "file.php";
// declaration
function foo()
{
// function body
}
But can you include
a file inside a function?
e.g.
<?php
// declaration
function foo()
{
// side effect: loads a file
include "file.php";
}
The thing to understand about this rule is the difference between declaration and execution. You may also think about it as loading of code vs. execution of code. When you load code, you do not expect it to do anything just yet. E.g.:
require_once 'utility_functions.php';
You include this file because you want to use some utility function which is in that file. You need to include this file to use any function in it, you can't not include the file. However, if that file goes off and produces some side effects, just by you including it, you've just gotten into a deep rabbit hole. For example, say the file always changed your error reporting settings. That would be majorly annoying. You'd always have to reset your error reporting every time you included this file:
require_once 'utility_functions.php';
error_reporting(E_ALL);
ini_set('error_display', false);
That's obviously madness and a source of potential problems.
On the other hand, once you execute code, you expect that code execution to do something, possibly even to have side effects. And you can control code execution, unlike whatever the file does simply by being included.
require_once 'utility_functions.php';
utility_do_something(); // side effects here are OK and/or expected