Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP parsing on includes

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.

like image 233
HyderA Avatar asked Apr 28 '26 04:04

HyderA


1 Answers

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.

like image 170
pingw33n Avatar answered Apr 29 '26 19:04

pingw33n