Prince Luo
Prince Luo

Reputation: 101

php require_once modify the local variable?

In my web page, I wrote:

<?php
//define('__PUBLIC__', $_SERVER['DOCUMENT_ROOT'].'/public'); 
$doc_public = $_SERVER['DOCUMENT_ROOT'].'/public';
echo "Before include...<==============>$doc_public";
?>
<?php require_once($doc_public.'/inc/head.php');  ?>
<?php echo "After include...<==============>$doc_public"; ?>

And the page shows: enter image description here

This firstly happened when I notice the fatal error in the footer, but the head is fine.

Although I can implement define or constant variable to avoid this, I am still curious how it happens.

P.S.: I run this under Apache with a port 8001. This is set in 【apache\conf\extra\httpd-vhosts.conf】. I am running more than one webapp under this site. I just share this information, as I am not sure this has anything to do with this case.

Thanks!

Upvotes: 0

Views: 238

Answers (1)

Andrea Olivato
Andrea Olivato

Reputation: 2545

When you require a file, if a variable is modified it affects the original script as well, that's how it's designed. Require doesn't create a secondary environment separated from the including file, it just adds the PHP code in sequence, exactly like if you had written the code in the initial file.

Have a look at the official PHP documentation, the first example is exactly the same as your case

http://php.net/manual/en/function.include.php

(include is the same as require, the latter just throws an error. For more info about differences between include and require http://php.net/manual/en/function.require.php)

Upvotes: 2

Related Questions