【问题标题】:Using variables with Include() in php [duplicate]在php中使用带有Include()的变量[重复]
【发布时间】:2020-07-14 00:54:51
【问题描述】:

此代码输出路径

function genPost() {
// Gives the full path leading to this file starting at root.
// eg. /var/www/html
$path = dirname(__FILE__);

// Lists the folders and files of the chosen path.
// FYI the variable is now an array!!!
$pathContents = scandir($path);

function makePath($key) {
    $path = dirname(__FILE__);
    $folders = scandir($path);
    $two = $folders[$key];
    $three = $path . "/" . $two;
    echo $three . "<br>";
    //echo include("$three");
}
$key = 0;
// array_key_exists() returns false when the key to the array doesn't exist
while (array_key_exists($key, $pathContents)) {
    makePath($key);
    $key = $key + 1;
}
}
echo genPost();

但是,当我将 while 更改为此时,它不会向浏览器输出任何内容。

while (array_key_exists($key, $pathContents)) {
    include "makePath($key)";
    $key = $key + 1;
}

我的问题是如何避免将目录放入包含中,而是使用变量告诉 php 解释器从哪里提取包含函数的文件。

【问题讨论】:

  • 我正在尝试制作一个用于在博客上显示帖子的脚本。这是了解如何动态操作 Include() 函数的实验的开始。
  • 我发现您的问题不清楚。我无法复制您试图描述的任何内容,因为我没有看到 getSum() 在任何地方声明或调用。你想echo include吗?
  • 我更新了帖子。很抱歉不清楚。让我知道这是否有帮助。
  • PHP 确实解析了双引号字符串中的变量——但不是函数调用。 include "makePath($key)"; 必须是 include makePath($key); 并且该函数需要返回路径,而不是回显它。
  • 回显包含不起作用。

标签: php web


【解决方案1】:

您使用包含字符串的问题(通常应该是表示路径的字符串,而不是函数调用),这将导致路径错误。

你的 makePath 应该是:

function makePath($key) {
    $path = dirname(__FILE__);
    $folders = scandir($path);
    $two = $folders[$key];
    $three = $path . "/" . $two;
    return $three;
}

当你需要使用它时:

while (array_key_exists($key, $pathContents)) {
   include makePath($key);
   $key = $key + 1;
}

【讨论】:

  • 天哪!就是这个!!我没有发现 echo $three 中的错字。 "
    ";也谢谢你对退货的建议!!!
猜你喜欢
  • 2014-07-13
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
相关资源
最近更新 更多