PHP passing variables via include files (relative

2019-07-21 02:27发布

问题:

I want to pass a variable defined in an include file, identity.php, to the parent file, which I'll call parent.php. When I include identity.php via it's relative path, the variable is available to the parent.php file. When I include identity.php via it's absolute path (to the application root), it doesn't work. Why is this?

File: identity.php

$g_groupid = 2;

File: parent.php

include('absolute_path_to_identity.php');
echo $g_groupid; //NOTHING!

However...
File: parent.php

include('../../identity.php'); //relative path to include file 
echo $g_groupid; //echos 2 as expected

I have verified that identity.php is included in both cases by echoing a "identity file is included message" (from within the identity.php file) which is displayed for both the relative and absolute includes. What could be the cause of this behavior?

回答1:

Did you try using realpath() ?

require_once(realpath('../../identity.php'));

Also, I recommend turning off error reporting if its not on already so you can make sure the file is indeed included, and get some more info on this. Add this on the top of your file :

ini_set("display_errors","On");
error_reporting(E_ALL);


回答2:

This sounds like your "absolute path" is an URL like http://www.example.com/folder/identity.php If that's the case PHP will fetch the code from the web server using HTTP, and so all PHP code will be evaluated before the file is included.

This will give the behavior you described with the echo troubleshooting as well.

An "absolute path" is on the form /home/user/public_html/folder/identity.php and is not the same thing as an URL.


Consider this:

identity.php

<?php
echo 'Is included';
$g_groupid = 2;
?>

When evaluated by the PHP interpreter this will result in this raw text:

Is included

If you include that raw text into parent.php it will behave as if it was raw HTML without any PHP code because there are no <?php tags in that raw text. Then consider this identity.php:

<?php
echo 'Is included <?php $g_groupid = 3; ?>';
$g_groupid = 2;
?>

Which will result in this:

Is included <?php $g_groupid = 3; ?>

What results do you get in your parent.php now? Is $g_groupid 2 or 3?



回答3:

Are you sure your absolute path is working?

I had similar issues and I use, in this case, always the full path through DOCUMENT_ROOT

include($_SERVER['DOCUMENT_ROOT']."/your_file_path.php");


回答4:

Hmm, try:

include('absolute_path_to_identity.php');
global $g_groupid;
echo $g_groupid;