Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP behavior of include/require inside conditional

If I place an include or require statement inside a conditional that evaluates to false, will the PHP interpreter skip the include file altogether, or will it load it just in case?

An example would be:

if ($some_user_var) {
    require 'this.php';
} else {
    //do stuff
}

I read somewhere that require will always be included by the interpreter regardless of the conditional, but include will not. If that's the case, just switching from require to include could mean a free speedup due to the reduced I/O and parsing overhead.

It probably makes a difference if I'm running a preprocessor like eAccelerator, but let's assume I don't.

like image 585
Jens Roland Avatar asked Oct 11 '10 13:10

Jens Roland


3 Answers

It will only be included if the condition is true. I don't know where you read otherwise, but they're wrong.

The only difference between include and require is that include will throw a warning if it fails, whereas require will throw a fatal error.

To confirm this, see the PHP manual page for require.

(ps - if you're doing conditional includes, depending on what the reaon is, you may consider using include_once() or require_once() instead)

like image 178
Spudley Avatar answered Nov 13 '22 23:11

Spudley


This is not correct. require will not include files that are wrapped in blocks where they are never called, the php interpreter does not ignore them. include and require have little to no difference performance-wise (for that matter neither do they have much of a difference from _once, though it is more significant).

like image 38
Explosion Pills Avatar answered Nov 13 '22 21:11

Explosion Pills


I read that somewhere too. The argument goes something like this:

If you put a condition around an include, PHP has no way of knowing if it is required or not until it starts to interpret the code and it can't interpret the code until it gets hold of all the variables and functions and therefore - files. So it LOADS UP all the files regardless of the condition and then drops them back out of the final "compilation".

Although then again, if you wrap a condition around a PHP file with an error in it, it doesn't break it. And if you declare a variable in an included file and then use the value of variable to determine whether or not to include it, it doesn't pick up its value:)

Maybe this used to be a problem in old versions of PHP?

I haven't tested it with regards to load speed and RAM usage - but I'd love to get a definitive answer to this. Is there ANY overhead involved with conditional includes?

like image 41
Enigma Plus Avatar answered Nov 13 '22 22:11

Enigma Plus