Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do require() and include() statement act differently while in a conditional statement?

I wanted to see if there was any reason beyond needing it or requiring it (hence the names). I stumbled upon this statement:

Unlike include(), require() will always read in the target file, even if the line it's on never executes. If you want to conditionally include a file, use include(). The conditional statement won't affect the require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed.

The way I am interpreting it is that includes inside conditionals that do not end up running, will not actually include it in there, which to me seems less costly to the server. I am just curious if this is true. I did not see it in the manual, so I am skeptical.

like image 268
Andy Avatar asked Nov 30 '25 16:11

Andy


2 Answers

If you have include inside a false statement, it will not get parsed. The same is true for require. The main and only difference is that require will check if the file exists even if it's never executed. Well, this has been my experience with it, at least.

So, both only happen once executed, but require will show an error if the file doesn't exist, regardless of whether it's executed.

like image 144
DanRedux Avatar answered Dec 02 '25 06:12

DanRedux


not exactly how it's implemented, but this should give you an idea of what the difference between the two is:

function require($file) {
   if (!is_readable($file)) {
      die("can't read $file");
   }
   include($file);
}

include reads in the file everytime you tell PHP to include it. the _once variants simply keep track of what's been included and only do the include once.

like image 45
Marc B Avatar answered Dec 02 '25 05:12

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!