Is include()/require() with "side effects" a bad practice?
Is doing something like
_________________________
//index.php
...
require("header.php");
...
_________________________
_________________________
//header.php
printHeader()
function printHeader(){
echo 'something';
...
}
_________________________
considered a bad practice to avoid?
I personally believe that the execution of a require()
(or require_once()
or include()
, that's not the point) call should only add a "link" to other functions/objects and never execute anything on its own. In other words in my opinion a require should behave in a very similar way to the import/using of other oo languages.
The example that I've written above is pret开发者_开发技巧ty trivial but obviously I'm writing also against every kind of "side effects". The define function or some tricks with sessions are other abuses that I have found often in some included files.
Yes, IMHO it's (very) bad practice unless very explicitly documented.
include
or require
(and their equivalents in other languages) should normally only introduce new functions into the current scope, and never trigger their invocation.
That's a question of general design, not personal preference. If you can design with personal preference, then it's your personal preference. Do whatever you like, use the language as a tool.
For example, if you use PHP as a replacement for server-side includes, it's pretty common that includes contain mostly HTML with some PHP fragments. Great sites were built with this. There is nothing bad with that kind of design in the real-world.
However if you need more fine-grained control you're mostly referring to objects instead of files. In that case I suggest you shouldn't have any include in your code, but an autoloader that requires as needed upon request by classname in your application.
The example you have in your question however looks like that there is not much concept behind it anyway, maybe it should allow having local variables inside an include, however that can be more easily achieved by including dynamically inside an include helper function like:
/**
* include a file with its own local scope.
*
* @param string path to include file
* @param array (optional) variables, keyed with variable name.
* @return mixed return value of include
*/
function include_helper()
{
if (!func_num_args())
{
return NULL;
}
elseif (2 === func_num_args() && is_array(func_get_arg(1)))
{
extract(func_get_arg(1), EXTR_OVERWRITE);
}
return include(func_get_arg(0));
}
And therefore spare to define a function inside each include having the same name as the include.
精彩评论