PHP: require vs require_once

PHP: require vs require_once

As PHP code grey up in size, it is reasonable to store part of code into external files. Thus making code more perceptible and making logical structure. It is a good question – how detailed code should be spitted? Single answer does not exist.

Include – is a php construction, allows to include some code located into external file into existing one. That’s mean, if code of function x() will stored into external file – file.php, this function will be available as soon, as this file is included. In case file does not existis – include will rise warning, require – fatal error after what future code execution will be terminated.

With the code becomes more complicated, more probably, that functions used in this code will be dependent from other functions, which mostly will be stored into external files. To avoid duplicating code inclusions, special php construction exists – require_once.

function A() {

  return 123;
}

require_once("fails_A.php")

function B() {

  return A();
}

Bencmarks shows, that require_once is up to 4 times slower than require. Searching google, you can find different figures and measurements, sometimes contradiction. Repeated file inclusion is evil by itself, because file should be read, code analysed and executed.

http://lv.php.net/manual/en/function.require-once.php#62838
http://peter.mapledesign.co.uk/weblog/archives/writing-faster-php-code-1-require_once

What to do?

Both inclusion processes can be positively affected by using absolute path instead of relative. i.e. /var/www/file.php instead of ../../file.php. If amount of inclusion is not significant, this difference might not be observed.

http://us2.php.net/manual/en/ini.core.php#ini.realpath-cache-size


Alternatives?

1. using include (or require) only once;
2. Involving __autoload();
3. class_exists('myClass') || require('path/to/myClass.class.php');
4. function_exists(’functionInFile’) && return; vai class_exists(’ClassInFile’) && return;
5. @include(“file.php”);

Error suppression is resource consuming process and should be avoided everywhere where it is possible. About that read in future articles ;)

http://www.techyouruniverse.com/software/php-performance-tip-require-versus-require_once

P.S. did I mentioned that calling of static method is faster that dynamics? Did, I?

 

» Rate it!

(0)

» Related articles

» Comments

No comments
* mandatory
* not public
Besucherzahler ukraina brides
website counter
vimeo youtube     myspace facebook twitter
where to eat in riga?