[英]PHP can't pass variable to included file
我试图找到这个解决方案:
file1.php
$name = "Jacob";
include ("file2.php");
file2.php
Hi there! <?php echo $name ?>
产量
Hi There! Notice: Undefined variable: name in /volume1/web/test/file2.php on line 9
需要帮助请://
你的代码运行正常。
如果您收到该错误,则file1.php肯定不会在全局范围内定义$ name。
Fyi,引自文档:
包含文件时,它包含的代码将继承发生包含的行的变量范围。 从那时起,调用文件中该行可用的任何变量都将在被调用文件中可用。 但是,包含文件中定义的所有函数和类都具有全局范围。
我的测试用php-5.3.3-pl1-gentoo(cli),以防你在使用的任何版本中都是PHP错误 - 但我怀疑:
[thiefmaster@hades:~]> cat inc1.php
<?php
$name = 'bleh';
include('inc2.php');
?>
[thiefmaster@hades:~]> cat inc2.php
Hi there! <?php echo $name; ?>
[thiefmaster@hades:~]> php inc1.php
Hi there! bleh
确保您的URL以file1.php
结尾,而不是file2.php
或包含file2.php
其他文件。 另外,尝试(加了两个文件还原到你贴什么位置<?php
之初file1.php
)排除周围的代码。
我有同样的问题,并修复如下:
$name = "Jacob";
include ("file2.php");
file2.php
$name = $name; //add this line
Hi there! <?php echo $name ?>
我无法解释为什么它应该像这样工作。 只是它奏效了。
我有时会被愚弄(为了被困的短暂)而忘记使用基本文件在线检查项目。
例如,如果使用名为index.php且包含inc.php的基本文件,请确保启动index.php而不是包含文件。
inc.php文件将在浏览器中显示错误,因为它没有链接到index.php变量,而index.php文件包含变量和包含。
我改用环境变量。 它解决了这个问题。
即
$_ENV["name"] = "Jacob";
在file2.php
里面
echo $_ENV["name"];
如果你想打印/使用$name
变量,那么你必须首先在file2
声明该变量,就像$name=""
,然后你可以轻松地使用它,而不需要声明,你将得到Undefined Variable
错误。
尝试使用此代码
global $name;
$name = "Jacob";
include ("file2.php");
**和file2.php里面
global $name;
echo "Hi there! ".$name;
我认为这会奏效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.