Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 354
JM4 Avatar asked Dec 09 '25 01:12

JM4


2 Answers

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.

like image 71
Pascal MARTIN Avatar answered Dec 10 '25 15:12

Pascal MARTIN


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.

like image 21
Pekka Avatar answered Dec 10 '25 16:12

Pekka



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!