views:

238

answers:

4

I'm including a file init.php which defines path constants. So if I include init.php in a file (index.php) and then in another file (layout/header.php)... is init.php parsed before being added to these files or is it added to the parent file and then the parent file is parsed as a whole?

EDIT: Why this is important is because init.php defines path variables relative to location of where it is parsed.

+3  A: 

Think of it as being copy-pasted into the file at the position where it was included. Use require_once or include_once if you don't want your stuff redefined.


There is no difference between including a .php or a .txt. You can include php in a .txt file and it will get parsed as long as you have the <?php openning tag.

Mark
Duplicate scripts is not the issue. And if it is not parsed, what is the difference between including files with extension .php and those with, let's say .txt?
gAMBOOKa
see edit ------
Mark
A: 

It depends if you use include or require. With include the text content of the included file is added to the parent and then the whole thing is parsed. With require the included file is first parsed and its content made available to the runtime, then processing continues with parsing the rest of the containing file.

If you want to make sure that the init file is only loaded once in a runtime of a request, then use require_once to make sure that it is only parsed once regardless of how many times you call it. Its a good idea to try to load your init file everywhere you need its constants, but use require_once to make sure you don't parse it more times then needed.

Guss
pingw33 is correct - `require` and `include` defer only in the severity of failure.
Guss
Also no text inclusion is performed, every php file is parsed as is.
pingw33n
+3  A: 

Actually include and require are identical in all except require will fail with E_ERROR while include will issue a warning. Also both of the statements are only activated when they actually executed inside script. So the following code will always work:

<?php
echo "Hello world";
if (0) require "non_existing.php";

The answer to your question is that index.php will be parsed first and executed. Then when include "init.php" encountered the file init.php is parsed and executed within current scope. The same for layout/header.php - it will be parsed first.

As already noted init.php will be parsed and executed each time include / require is called, so you probably will want to use include_once or require_once.

pingw33n
A: 

Use require_once to include your init.php file in your app. require_once assures that the file is included only once.

Salman A