William T Wild
William T Wild

Reputation: 1032

PHP include_once or require_once in a loop

Quick question about include/requre_once . I have some code that is common to a few pages that I feel would be better to be in a file to call from each page rather than code repetition.

I call the include_once in a while loop and what I noticed is that I have to use include('file.php') or it will literally load it (and display it) only once . I guess what I assumed ( incorrectly) is that it will load it on the first loop and retain the code in a cache to avoid having to access the disk each iteration of the loop.

I looked around for a "load_once_and_cache" type of command but did not find anything.

Does anyone have any suggestions for this or is putting the code in each page the only option.

Thanks again!

Upvotes: 1

Views: 5706

Answers (2)

Victor Nițu
Victor Nițu

Reputation: 1505

Since the air around you post smells like a complex structure and massive amounts of code, I'm going to assume you are using OOP techniques in order to get things done.

In this case, maybe you will want to consider autoloading classes as a more efficient and fast method:

http://php.net/manual/en/language.oop5.autoload.php

You will also need to read the comments in order to fully understand what's going on and find some really methods to manage various situations.

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270647

This is a pretty inefficient method of getting content into a loop. PHP would need to read the file from disk on each include() call. You're much better off creating a function (which may be in the included file). Include the file once, which defines the function, then call the function in your loop.

It isn't always good practice to rely on the output of an included file, except perhaps when coding a view (even then I'd think twice before doing it). Requiring a file to be included inside a loop creates a strange mix of flow control and file inclusion that can be difficult to debug and maintain.

Upvotes: 6

Related Questions