PDA

View Full Version : do you ever use require_once() ?



Birmingham
12-22-2006, 05:51 PM
does anyone here ever use require_once() ? if so, in what kind of situation do u use it? any example code?

Twey
12-22-2006, 06:24 PM
Everywhere possible. Makes debugging one heck of a lot easier.

djr33
12-23-2006, 01:43 AM
require is the exact thing as include, except that it will make the script fail is the file is not included.
require_once and include_once are a kinda weird variation that make sure it is only included once, so it isn't accidentally included later in the page.
Generally, it seems that your own logic could be used to avoid this mistake, but there might be a situation in which you have different if statements, and, possibly, more than one is true at different times, each with a require statement.

mwinter
12-24-2006, 12:02 AM
require_once and include_once are a kinda weird variation that make sure it is only included once, so it isn't accidentally included later in the page.
Generally, it seems that your own logic could be used to avoid this mistake, but there might be a situation in which you have different if statements, and, possibly, more than one is true at different times, each with a require statement.

Think simpler than that. Think analogous to header files in C or C++. These contain declarations that will be used many times in many different compilation units, and redeclaration will lead to a fatal error. The same is true for PHP: class redeclaration will cause an error.

Consider, for instance, some user-defined exception classes. In a framework, or some other reusable collection of components, these classes will be used many times. What's more, client code that uses the framework will include different parts of it. It would add a huge burden to authors if they have to examine every include, and the includes in those files, and so forth for collisions. It's also inefficient and cumbersome to conditionally include. Using include_once and require_once, the author can move all of this responsibility onto the PHP interpreter.

Mike

djr33
12-24-2006, 03:50 AM
Hmm... yeah.
Like forums that have one php page which is basically just required values, like the password to the database and such, and then that's included into each page.

motormichael12
12-24-2006, 06:56 PM
Example of when to use require_once:

In a bulletin board software I downloaded it has:



require_once("chmod_check");

This allows it to check if the files are chmod 777, which is required for that software. It then deletes the file when you are done using it.

Also you cna just use if(fileexists(filename.ext)) { require(filename.ext) }

Twey
12-26-2006, 08:25 PM
That's not the same thing at all, even overlooking the syntax errors.