6

I know that include_once and require_once will only allow the called script to run once. My question is this: If I don't use _once, would it always run multiple times? Does it run more than once by default? I searched for answers, but I found none.

brenjt
  • 15,997
  • 13
  • 77
  • 118
  • http://stackoverflow.com/questions/3546160/include-include-once-require-or-require-once and http://stackoverflow.com/questions/3626235/what-is-the-difference-between-php-require-and-include after Googling "difference between include and include_once php" there are many more that I found, those are only two out of many. – Funk Forty Niner Nov 25 '13 at 02:56
  • it depends on how you design your script structure. You can include it as many times as possible. – Raptor Nov 25 '13 at 03:07

4 Answers4

7

include runs one time every time you write it. The point of using include_once is that you can do

include "myfile.php"; // Include file one time
include "myfile.php"; // Include file again

This is perfectly legal, and in some cases you would want to do that.

The problem is that if you for example define a function in this file, php complains that you can't define that method more than once (because the name is already taken).

include_once makes sure that the same file is not included more than once, so if you do:

include_once "myfile.php"; // Include the file one time
include_once "myfile.php"; // This is ignored

...Only one include is performed.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
2

It's not that it runs multiple times, but if you had a file that included multiple different things and one of those thigns includes one of the other already included things you'd have them being included multiple times, which could be bad.

John V.
  • 4,652
  • 4
  • 26
  • 26
2

If you don't include _once it will run as many times as you call it within your script. There is no default number of runs (somehow I get a feeling that you think it might run several times just by itself, but no) - one include = one run.

Shomz
  • 37,421
  • 4
  • 57
  • 85
0

Yes, if you use include instead of include_once (or require instead of require_once) the indicated file will be included and executed a second time if you ask for the same file a second time.

This is useful for referencing common code that you need to execute at this point in the including page, as opposed to the normal reason for include files which is to declare functions and classes. The former is an old programming technique.

staticsan
  • 29,935
  • 4
  • 60
  • 73