duanchou6534 2018-10-24 13:44
浏览 128
已采纳

不能从另一个文件中使用php变量[重复]

like my title says, whenever I try to use my variables from another php file, it doesn't work (Undefined variable). I did declare them in the file that I'm including. For example, I have this file called variables.php that have this in it:

<?php
$DEBUG = TRUE;
$mysqli = new mysqli("127.0.0.1", "root", "", "29185917-database");
$DEBUG_LOG_FILE = "../log";
?>

And then I have another file called debug.php that tries to use the variable 'DEBUG' but it cannot access it. Here is my debug.php file:

<?php
require_once 'variables.php';
function echo_debug(string $message)
{
    if($DEBUG) {
        echo $message;
    }
}
?>

Whenever I try to use my function echo_debug I get the error message : Undefined variable 'DEBUG'. Any help on this problem is appreciated :).

</div>
  • 写回答

3条回答 默认 最新

  • dqwcdqs358367 2018-10-24 13:49
    关注

    Functions have their own scope. The variable is accessible, just not from inside the function.

    You could pass $DEBUG as a parameter

    function echo_debug(string $message, bool $DEBUG)
    

    Then you would call it as

    echo_debug("comment that will help me debug in dev mode", $DEBUG);
    

    Another option is to declare DEBUG as a constant,

    define('DEBUG', true);
    $mysqli = new mysqli("127.0.0.1", "root", "", "29185917-database");
    $DEBUG_LOG_FILE = "../log";
    

    Then, in your function you would check for that constant:

    function echo_debug(string $message) {
        if(DEBUG) { ... }
    }
    

    You could also use the global keyword, right above your if(), try to add global $DEBUG;.

    require_once 'variables.php';
    function echo_debug(string $message)
    {
        global $DEBUG;
        if($DEBUG) { ... }
    }
    

    But generally the other two solutions are better, global variables are sometimes frowned upon.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用