I have 3 different files-
fileMainIncludeEverywhere.php
...
include_once('fileMinorInclude.php');
?>
fileMinorInclude.php
...
include_once('fileMainIncludeEverywhere.php');
...
fileToRun.php
...
include_once('fileMainIncludeEverywhere.php');
...
I have a lot of files like fileToRun.php.
Currently I'm not facing any errors in my code, but I want to know if there's any case where this would fail?
I think no error in this case. Because include_once will only load the file for the first time then upcoming load request will be rejected for the same file.
So from your example:
fileToRun.php will load fileMainIncludeEverywhere.php (first call)
fileMainIncludeEverywhere.php will load fileMinorInclude.php (first call)
fileMinorInclude.php will call to load fileMainIncludeEverywhere.php but it will be rejected as it has been already loaded in first step.
Hope it will help.
include_once:
The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included just once.
Here "code from a file" also entails the executed PHP file.
Note it's generally best practice to use require_once() instead of include_once() unless you've got a specific reason for using include_once() (like say including optional template components). This because require_once() will terminate (fail fast) if the required resource is not found, and not finding it normally should be a terminal failure.
Related
I am trying to include 2 php file in two separate <td> tags in the same table.
<td><?php include 'login.php';?> </td>
<td><?php include 'register.php';?> </td>
Both the php files include another php file for connecting to a database (eg. <?php include 'database.php';?>
Now, the problem is, the second file doesn't show up in the table. First file works.
Php files work independently. No problem with the code.
I removed the include in 1.php and everything worked fine - ie. both the files show up in table.
My conclusion is, it goes on including indefinitely. Now, how do I solve this?
regards
Ganesh Kumar
You can use include-once
The include_once statement includes and evaluates the specified file
during the execution of the script. This is a behavior similar to the
include statement, with the only difference being that if the code
from a file has already been included, it will not be included again.
As the name suggests, it will be included just once.
i.e.:
include_once('database.php');
include_once('login.php');
include_once('register.php');
You actually have several options, now that I think about it.
Require_once:
require_once('database.php')
This is the most accepted method for files such as this one that you describe, as it will hard-fail if the file cannot be included. For files that do program instantiation (I.e. database connection) this method is preferred.
Include_once:
include_once('login.php')
I've never found a reason to use this statement over require_once; however, that said, it doesn't mean there isn't one. If you have a file that does some instantiation of something related to your programme that isn't mission-critical, then you could suppose to use this directive over the other.
Define Include Constants:
This method requires a bit more explanation: instead of starting your included file (database.php in our example) off with the code for it, start it off in a manner similar to C/C99/C++.
<?php
if (!defined("INCLUDED_DATABASE"))
{
define("INCLUDED_DATABASE", true);
// add main body of file here
}
?>
This method basically accomplishes the same thing as the include_once and require_once, except that in no circumstances will it ever actually process the body twice in one request, even if you forget to use _once as a suffice to your include/require method. This goes back to the old days of C/C99/C++
where including a file twice would hard-fail the compiler, as duplicate definitions would take place.
Personally, I have always preferred the last option: it's the most strict. Yes, require_once and include_once when used diligently will have the same effect, but suppose someone (not even you necessarily) is modifying the application and accidentally does an include or require without the _once suffix, they will be having a bad day. This method prevents that.
That said, I still use a require_once when necessary, and a require if it can be included multiple times. (Files with that designation are not designed with the define construct.)
I am calling similar PHP scripts from different locations in WordPress.
They all have in common that they call another php file (genlib.php) which its some kind of library with a large number of php functions.
When I ran into the "cannot re-declare function ... in genlib.php" error, I wrapped each function into an "if !function_exists" condition to avoid this.
This is ugly because I have to do it so many times.
How can I avoid this on the level where I include the genlib.php file in my scripts?
I believe using include_once or require_once in all files that include the file genlib.php should solve this problem.
Update: Based on the OP's comment, it appears that this solution does not work for multiple different scripts loading libraries which include_once genlib.php. In this case, the OP may have to regress to using a guard statement wrapping the entire genlib.php.
if (!defined('GEN_LIB_PHP')) {
define('GEN_LIB_PHP', true);
// Rest of code for genlib.php
}
Use include_once() for the file. This prevents the system from running the code again, if the file was included before. The same applies for requrie_once().
I want to write a script that creates a PHP file with some definitions (define(..., ...);) and then within this script i want to run more commands that uses the definitions i just defined in the newly created php file. for this to work i am guessing i could do something like that :
create file (say def.php) and write definitions to it
require_once 'def.php';
run commands that uses definitions from def.php
will this work? if not what is the right way of doing it?
It will work, you can use it but if the file does not exist then it will call exit() in the middle of your page so you will get a half loaded page with an error message.
I think the eval() or anonymous functions (closures) should be better.
http://www.php.net/manual/en/function.eval.php
http://php.net/manual/en/functions.anonymous.php
Among include, include_once, require and require_once I always just use require_once. Many third-party frameworks just use require_once as well.
Can anybody please describe a real scenario that another construct must be used?
IMHO there is no real scenario that fits include and include_once because of two reasons:
It's highly unlikely that your intention is to include a file and at the same time you don't really care if it's included (e.g. if the file does not exist and execution continues).
Even if that is the case, include will emit a warning which is bad style (zero-warning code is a good thing to strive for). You can prevent this most of the time with a check like is_file, but then you know that the file does exist so why not require it?
For require vs require_once: if a file can legitimately be parsed more than once (e.g. an HTML template) use the former. If it brings code inside your application (the vast majority of cases) use the latter.
The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.
The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.
The only difference between the include/require and include_once/require_once statements is how many times a given file will actually be loaded. When the include_once/require_once statements are used, the file cannot be loaded or executed multiple times. If an attempt is made to load a file twice using one of these two methods, it will be ignored. Because it is unacceptable to define the same function multiple times within a script, these functions allow the developer to include a script as needed without having to check whether it has been previously loaded.
<?php
include ('library.inc');
$leap = is_leapyear(2003);
require ('library.inc');
$leap = is_leapyear(2003);
?>
If both statements will allow the current script to execute the code in a separate file, what is the difference between the two?
There are two major differences:
the first is the capability to return values and the second is under what circumstances the requested file is loaded. When an include statement is used, PHP delays the actual loading of the requested file until the script reaches the point of executing the include statement and replaces the include statement with the contents of the file. Conversely, in the case of the require statement, the require statement is replaced with the contents of the requested file regardless of whether the require statement (and thus the contents of the file) would have executed in the normal progression of the script.
Quoting above paragraph from http://82.157.70.109/mirrorbooks/php5/067232511X/ch01lev1sec8.html
NOTE
The capability to return values from external files is limited only to the include and include_once statements. The require and require_once statements cannot be used in this fashion.
require give Fatal error but include give Warning
The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal E_COMPILE_ERROR level error.
The same difference applies also for include_once and require_once.
When use include and when use require, is described very good in answers to Difference between require, include and require_once?
From the my point of view, there are 2 things.
if you have something, which is absolutely required to be present in your application, you should use require/require_once to include such definitions. That way you'll get fatal errors instead of warnings and during development that will simplify finding problematic code.
if you're including external resource or something which may be missing, it should be included with include/include_once in order to be able to suppress possible include errors using # operator.
This question already has answers here:
Difference between "include" and "require" in php
(7 answers)
Closed 8 years ago.
I want to know when I should use include or require and what's the advantage of each one.
require requires, include includes.
According to the manual:
require() is identical to include() except upon failure it will produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.
As others have said, if "require" doesn't find the file it's looking for, execution will halt. If include doesn't file the file it's looking for, execution will continue.
In general, require should be used when importing code/class/function libraries. If you attempt to call a function, instantiate a class, etc. and the definitions aren't there, Bad Things will happen. Therefore, you require php to include your file, and if it can't, you stop.
Use include when you're using PHP to output content or otherwise execute code that, if it doesn't run, won't necessarily destroy later code. The classic example of this is implementing a View in a Model/View/Controller framework. Nothing new should be defined in a view, nor should it change application state. Therefore, it's ok to use include, because a failure won't break other things happening in the application.
One small tangent. There's a lot of conflicting information and mis-information out there regarding performance of include vs. require vs. require_once vs. include_once. They perform radically different under different situations/use-cases. This is one of those places where you really need to benchmark the difference in your own application.
The difference is this:
include will not fail if it cannot find the resource, require will. Honestly, it's kind of silly that include exists at all, because if you are attempting to load a resource you are pretty much counting on it being there. If you are going to use anything, I would recommend using require_once always, that way you don't run into collisions (ie, if another script is requiring the same file) and your code always works as intended because you know the resources you are including are there (otherwise it is failing).
If a file is optional, include it. For example, you might have a file 'breaking-news.txt' that gets created when there's breaking news, but doesn't exist when there's none. It could be included without the script breaking if there's no breaking news.
If the file is required for the rest of the script to function properly, require it.
Per http://www.alt-php-faq.org/local/78/:
Unlike include(), require() will always read in the target file, even if the line it's on never executes. If you want to conditionally include a file, use include(). The conditional statement won't affect the require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed.
In simple language if we use require we must sure that the file is existing in that era while it is not necessary in case of include. But try to make sure file exist.
Include and require are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
You can understand with examle
include("test.php");
echo "\nThis line will be print";
Output :Warning: include(test.php): failed to open stream: No such file or directory in /var/www/........
This line will be print
require("test.php");
echo "\nThis line will be print";
Warning: require(test.php): failed to open stream: No such file or directory in /var/www/....
Require() and include() are the same with respect to handling
failures. However, require() results in a fatal error and does not
allow the processing of the page. i.e. include will allow the script
to continue.