JM4
JM4

Reputation: 6798

Does PHP require, require_once, or include automatically read the file at page load?

I have several pages which use the include or require language constructs within PHP. Many of these lie within IF, ELSE statements.

I do realize that a page will not load at all if a require'd file is missing but the main purpose of including this way is to:

1) reduce code clutter on the page

2) not load the file unless a statement is met.

Does issuing an include or require statement load the file regardless (and thus eliminating the benefits I was trying to achieve by placing within the if/else statement?

Brief example:

<?php


$i = 1

if($i ==1) {

      require_once('somefile.php');

} else {

     require_once('otherfile.php');
}

?>

At page load, are both files checked AND loaded?

Upvotes: 2

Views: 2436

Answers (4)

mario
mario

Reputation: 145512

The include and require constructs are only evaluated when passed. The files are only read when your expression is met.

It's simple to explain by considering that the constructs might contain variables:

require_once("otherfile-{$i}.php");

That's supported. But it could not possibly work before PHP runs over that particular line, because it needs to know the state of $i to load the right file.

Upvotes: 2

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

If you place an include/require statement in the body of an if (or else), it'll be executed if the if's condition is true.

if ($a == 10) {
    // your_first_file.php will only be loaded if $a == 10
    require 'your_first_file.php';
} else {
    // your_second_file.php will only be loaded if $a != 10
    require 'your_second_file.php';
}


And, if you want, you can test this pretty easily.
This first example :

if (true) {
    require 'file_that_doesnt_exist';
}

will get you :

Warning: require(file_that_doesnt_exist) [function.require]: failed to open stream: No such file or directory
Fatal error: require() [function.require]: Failed opening required 'file_that_doesnt_exist'

i.e. the require is executed -- and fails, as the file doesn't exist.


While this second example :

if (false) {
    require 'file_that_doesnt_exist';
}

Will not get you any error : the require is not executed.

Upvotes: 9

Pekka
Pekka

Reputation: 449783

At page load, are both files checked AND loaded?

No, at least not since (IIRC) PHP 4.0.1.

If you want to reduce include clutter, and you are working with mainly object-oriented code, also take a look at PHP's autoloading.

Upvotes: 4

dialer
dialer

Reputation: 4844

No, only one of those files would be loaded.

Upvotes: 2

Related Questions