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.
It depends if you use
include
orrequire
. Withinclude
the text content of the included file is added to the parent and then the whole thing is parsed. Withrequire
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 userequire_once
to make sure you don't parse it more times then needed.Think of it as being copy-pasted into the file at the position where it was included. Use
require_once
orinclude_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.Actually
include
andrequire
are identical in all exceptrequire
will fail withE_ERROR
whileinclude
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:The answer to your question is that
index.php
will be parsed first and executed. Then wheninclude "init.php"
encountered the fileinit.php
is parsed and executed within current scope. The same forlayout/header.php
- it will be parsed first.As already noted
init.php
will be parsed and executed each timeinclude
/require
is called, so you probably will want to useinclude_once
orrequire_once
.