Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, how does include() exactly work?

Tags:

php

How does include('./code.php'); work? I understand it is the equivalent of having the code "pasted" directly where the include occurs, but, for example:

If I have two pages, page1.php and page2.php, of which I would need to manipulate different variables and functions in ./code.php, does include() create a copy of ./code.php, or does it essentially link back to the actual page ./code.php?

like image 567
John Zimmerman Avatar asked Aug 24 '12 23:08

John Zimmerman


People also ask

What is the Diffrences between function include () and require () in PHP codes?

The only difference is — the include() statement will only generate a PHP warning but allow script execution to continue if the file to be included can't be found, whereas the require() statement will generate a fatal error and stops the script execution.

What is include path in PHP?

The PHP Include Path is a set of locations that is used for finding resources referenced by include/require statements. Note: Adding libraries or external projects elements to your project's Include Path will also make elements defined in these resources available as content assist options.


2 Answers

See the manual.

If you include a text file, it will show as text in the document.

include does not behave like copy-paste:

test.php

<?php
echo '**';
$test = 'test';
include 'test.txt';
echo '**';
?>

test.txt

echo $test;

The example above will output:

**echo $test;**

If you are going to include PHP files, you still need to have the PHP tags <?php and ?>.

Also, normally parentheses are not put after include, like this:

include 'test.php';
like image 85
uınbɐɥs Avatar answered Oct 04 '22 04:10

uınbɐɥs


Basically, when the interpreter hits an include 'foo.php'; statement, it opens the specified file, reads all its content, replaces the "include" bit with the code from the other file and continues with interpreting:

<?php
echo "hello";

include('foo.php');

echo "world";

becomes (theoretical)

<?php
echo "hello";

?>
{CONTENT OF foo.php}
<?php

echo "world";

However, all this happens just in the memory, not on the disk. No files are changed or anything.

like image 43
Niko Avatar answered Oct 04 '22 06:10

Niko