I was toying around with printing some formatted sequential data, a module to be precise, within a loop. Something like:
foreach ($data as $row){
//echo the formatted data for $row;
}
I started wondering, are there any detriments /advantages to using a function over an include? eg.:
foreach ($data as $row){ function output($data); }
function output($d){ echo "<h1>$d['title']</h1>\n<p>$d['intro']</p><div>$d['story']</div><p>$d['story']</p>"; }
vs
`foreach ($data as $row){ include('module.php'); }`
where module.php is
I often find including a file much more easier to work with and less messy. When you have to reiterate an output so many times, it just makes it messy for you when you have to redo the output strings. It is also good practice to separate logics, this way, you can manage things in a much easier way.
That’s just how I see it. Not really an advantage.
the function might be in memory and more efficient. Benchmark tests would need to be run to know for certain, but I’m assuming any difference would be negligible especially for more trivial code.
I tend to go for readability and maintenance over efficiency and leave micro-optimization for efficiency sake until a problem becomes noticeable.
The advantage of a function is that it needs to explicitly state its dependencies, whereas an include automatically uses the available variables (so you have a hell of a time figuring out where that variable that the include uses comes from or even what it’s supposed to contain).