PHP 无法将变量传递给包含的文件

标签 php variables include

我试图找到解决这个问题的方法:

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。

仅供引用,引用自文档:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

我使用 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

关于PHP 无法将变量传递给包含的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4356405/

相关文章:

php - 在 Elastic Beanstalk 上更改 php.ini

javascript - 如何将 CSS 样式添加到 javascript

javascript - 在方法 JQuery 之外使用我的变量

c - 哪个文件应包含我的 c 项目中的库?

html - 如何在 HTML BASE 标记后使用本地 URL

javascript - 尝试更改表单提交上我的提交输入的值

php - 单个产品页面中的 WooCommerce added_to_cart 委托(delegate)事件

php - 如何使用函数连接到数据库以及如何使用查询?

mysql - 如何将输入的参数值与存储过程mysql中的变量进行比较?

php include语句无法打开流到当前目录上方目录中的文件