PHP parsing on includes

2019-05-10 18:20发布

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条回答
叛逆
2楼-- · 2019-05-10 19:07

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.

查看更多
Anthone
3楼-- · 2019-05-10 19:19

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.

查看更多
Anthone
4楼-- · 2019-05-10 19:20

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.

查看更多
登录 后发表回答