【问题标题】:How use a php variable declared in the parent file in an included file如何在包含文件中使用父文件中声明的 php 变量
【发布时间】:2018-07-29 05:20:31
【问题描述】:

我正在尝试将 php 变量 $shareURL = "someURL"; 从 test.php 的父页面传递到 commentTest.php 的包含文件中。这可能吗?如果是,请帮忙。

父文件 = Test.php

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    <?php 
    $shareURL = "someURL";
    echo "$shareURL";
    include "http://domainName.net/assets/includes/commentTest.php"; 
    ?>
</body>
</html>

PHP 包含的文件 = commentTest.php

<?PHP 
echo "<div class='fb-comments' data-href='$shareURL' data-num-posts='5' data-width='100%'></div>";
?>

HTML 输出源

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    someURL<div class='fb-comments' data-href='' data-num-posts='5' data-width='100%'></div></body>
</html>

【问题讨论】:

  • secure.php.net/manual/en/function.error-reporting.php 向您展示了什么?包括一个外部网址可能不会让你。充其量,您可以尝试改用file_get_contents()。请参阅包含 secure.php.net/manual/en/function.include.php 的手册
  • 你应该没问题,但要小心不要把它变成'spagetti'代码。因为它,我停止使用这种方法。另外,我建议更换“可选”结束标签?&gt;,因为它可以在包含末尾添加不需要的空格。
  • @Mr.B 我还是建议你使用匿名类,你试过了吗? $shareURL = new class{ public function __toString() { return "http://".$_SERVER['SERVER_NAME'] 。 $_SERVER['REQUEST_URI']; } };
  • 这个不能用session来应用吗?
  • 您需要按路径包含文件才能使用,例如:include 'assets/includes/commentTest.php';

标签: php variables scope include


【解决方案1】:

谢谢大家!

您的 cmets 和答案帮助我找到了我需要的解决方案。

$root = dirname(__FILE__);
include "$root/assets/includes/commentTest.php";

显然,我的根目录在 /var/www/html,而不是在 URL 中的 TLD 之后。

【讨论】:

    【解决方案2】:

    将您的 Test.php 更改为:

    include "/assets/includes/commentTest.php";

    【讨论】:

    • 这实际上是一个正确的答案,如果你给出了 OP 需要进行此更改的原因,我会加一分
    • 我不得不使用这个$root = dirname(__FILE__); include "$root/assets/includes/commentTest.php";
    猜你喜欢
    • 2011-08-30
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 2011-01-13
    • 2017-12-18
    • 2011-05-05
    相关资源
    最近更新 更多