Includes () / require () with "side effects" bad practice?

Does something like

_________________________ //index.php ... require("header.php"); ... _________________________ _________________________ //header.php printHeader() function printHeader(){ echo 'something'; ... } _________________________ 

considered bad practice to avoid?

I personally believe that making a call to require() (or require_once() or include() , not dots) should add only a reference to other functions / objects and never do anything on its own. In other words, in my opinion, the requirement should behave very much like importing / using other OO languages.

The example I wrote above is pretty trivial, but obviously I am writing against all kinds of “side effects” as well. The definition function or some session tricks are other abuses that I often encountered in some of the included files.

+4
source share
2 answers

Yes, IMHO this is a (very) bad practice , unless explicitly documented .

include or require (and their equivalents in other languages) usually should only introduce new functions into the current scope and never trigger their call.

+5
source

This is a matter of general design, not personal preference. If you can design with personal preferences, then these are your personal preferences. Do anything, use the language as a tool .

For example, if you use PHP as a replacement for the server side, it is quite common, including mostly HTML with some PHP fragments included. Great facilities were built with this. There is nothing wrong with this design in the real world.

However, if you need finer-scale management, you mostly refer to objects instead of files. In this case, I suggest that you do not include any inclusions in your code, but an autoloader, which, if necessary, requires, upon request, the class name in your application.

However, the example that you have in your question looks like there aren’t many concepts for it anyway, maybe this should allow you to have local variables inside include, however this is easier to achieve by including dynamically inside the auxiliary helper function, eg

 /** * include a file with it 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)); } return include(func_get_arg(0)); } 

And so the functions that are spare to the definition inside each include the same name as include.

+2
source

All Articles