【问题标题】:Trouble calling a variable from another .php file从另一个 .php 文件调用变量时遇到问题
【发布时间】:2014-11-10 20:58:01
【问题描述】:

以前也有人问过类似的问题,但是在仔细研究了几个工作示例之后,我无法让它为我工作。

我正在尝试访问在 insert-name.php 中声明的变量 $nameValues

insert-name.php 是第一个运行的脚本:

 error_reporting(-1);
$nameValues  = "'".implode("', '", array_values($nameArray))."'";
print_r($nameValues); // returns the expected variable

insert-answer.php 是要运行的第二个脚本:

 error_reporting(-1);
require "insert-name.php";
if (isset($nameValues)) {
   print_r("nameValues variable:" . $nameValues);
} else {
   echo "variable nameValues does not exist";
}
//returns nameValues variable:'' indicating that $nameValues exists but is empty

两个 .php 文件都存储在我的网络服务器上的同一个文件夹中。我试过同时使用requireinclude 语句。我成功地使用require 语句在两个脚本中连接到我的数据库,但不知道为什么它不适用于insert-name.php

编辑:

没有错误报告。 if语句返回“nameValues variable:''”表示$nameValues变量存在但为空。

我还尝试将 require "insert-name.php"; 替换为 require __DIR__."/insert-name.php";,它从 if 语句中返回“变量 nameValues 不存在”。

因为两者都没有给出致命错误,所以require 语句都成功访问了 insert-name.php 文件,但我不知道为什么一种方法认为$nameValues 不存在而另一种方法认为$nameValues 为空.

【问题讨论】:

  • 试试require __DIR__."/insert-name.php";
  • 另外,请尽早在脚本中添加error_reporting(-1); 并发布任何弹出的错误。
  • 谢谢尼克,我忘了在这里添加error_reporting。没有显示错误。
  • 好的,现在用 var_dump 替换 print_r 让我们确保我们得到一个空字符串,而不是 FALSE、0 或 NULL
  • 另外,如果添加__DIR__ 会改变输出,这意味着这是问题的一部分。这是因为包含路径在 PHP 中的工作方式。现在,我希望您确保始终使用__DIR__

标签: php variables require


【解决方案1】:

从另一个文件访问变量没有问题,就像您提供的那样,它们在同一范围内(一个不在函数内等)。在你的情况下,它看起来只是你如何调用print_r() 的一个例子

当您执行print_r('nameValues variable:" . $nameValues) 时,您将$nameValues 转换为字符串。

尝试这样的事情来转储你的$nameValues

error_reporting(-1);
require "insert-name.php";
if (isset($nameValues)) {
    echo "nameValues variable: ";
    print_r($nameValues);
} else {
    echo "variable nameValues does not exist";
}

【讨论】:

    【解决方案2】:

    如你所说:

    returns nameValues variable:''

    我忽略了一个细节,最后的引号。当你在 PHP 中回显一个字符串时,它只打印内容(不打印引号,除非它们在字符串中)。

    实际上这一切只是意味着$nameArray 是空的,所以请检查生成它的脚本。此外,由于implode() 的工作方式,array_values() 在这里完全是多余的。

    简单的测试方法是echo count($nameArray);。如果输出为“0”,则数组为空。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 2020-02-09
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多