Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would a script be included twice in PHP? [duplicate]

Tags:

include

php

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.

like image 863
DataRaiderGame Avatar asked Nov 25 '13 02:11

DataRaiderGame


People also ask

Can we use include two times in a PHP page?

Yes, you can include as many times as you wish.

What is the difference between include and include_ once in PHP?

The include() function is used to include a PHP file into another irrespective of whether the file is included before or not. The include_once() will first check whether a file is already included or not and if it is already included then it will not include it again.

What is include in PHP?

The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.


2 Answers

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.

like image 111
OptimusCrime Avatar answered Oct 11 '22 01:10

OptimusCrime


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.

like image 37
John V. Avatar answered Oct 11 '22 01:10

John V.