PHP头条
热点:

php两次include后,第一个include里的变量无效了解决方法


php 两次include后,第一个include里的变量无效了
目录结构
+ root
  index.php     
  config.php    
  +c
     index.php

root/config.php 里的内容
$shell['jquery'] = "jquery 1.4";
?>

root/index.php 里的内容
include "config.php";
print $shell['jquery'];
?>

root/c/index.php 里的内容
include "../index.php";
?>

访问root/index.php返回
jquery 1.4

访问root/c/index.php返回
Notice: Undefined variable: shell in H:\software\dev\php\xampp\htdocs\phptest\index.php on line 3


请问,两次include 后变量为什么会失效呢?正确的做法应该是怎样做?
谢谢大家了
       php 分享到:
------解决方案--------------------
首先,解析顺序如下

1.文件路径是绝对路径?是, 包含, 解析结束。不是, 进入下一步。
2.文件路径是相对路径(就像你的"../index.php")?是, 跳过include_path, 解析相对路径。不是,下一步。
PS:相对路径的基点, 永远是“当前工作目录”.即你在这个目录里执行了脚本,不一定是脚本文件所存在的目录
比如你在/root里执行了`php /var/www/index.php`,“当前工作目录”是/root而不是/var/www/,/var/www是
current_script_dir。
3.php.ini中的include_path,比如".:somepath:current_script_dir"。根据DEFAULT_DIR_SEPARATOR常量(这里是":")分割出待处理列表
"."(当前工作目录),"somepath(你自定义的目录)","current_script_dir"这三个
把包含的文件名附加这些路径后面, 逐个尝试。

所以你的问题就变成



#访问root/c/index.php

include "../index.php";  #执行第二步,include进/root/index.php

include "config.php";    
#执行第三歩,当前工作目录为/root/c,current_script_dir也为/root/c,
#估计你也没有自定义include_path,所以尝试包含/root/c/config.php,没有这个文件

print $shell['jquery'];
#Undefined variable
?>



这是我的理解,欢迎各位交流与指正

www.phpzy.comtrue/phprm/12413.htmlTechArticlephp两次include后,第一个include里的变量无效了解决方法 php 两次include后,第一个include里的变量无效了 目录结构 +root index.php config.php +c index.php root/config.php里的内容 $shell['jquery']="jquery1....

相关文章

相关频道:

PHP之友评论

今天推荐