duanchou6534
duanchou6534
2018-10-24 13:44

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

  • variables
  • file
  • 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 dqwcdqs358367 3年前

    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.

    点赞 评论 复制链接分享
  • dongtu0363 dongtu0363 3年前

    do like this:

    function echo_debug(string $message,$data)
    {
        if($data === TRUE) {
            echo $message;
        }
    }
    

    call function:

    require_once 'variables.php';
    $message = "comment that will help me debug in dev mode";
    $output = echo_debug($message,$DEBUG);
    print_r($output);
    
    点赞 评论 复制链接分享
  • doufutao4428 doufutao4428 3年前

    As per my comment, you can also use a constant and avoid the variable issue altogether.

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

    Then in the function check if the constant has been defined

    <?php    
    require_once 'variables.php';    
    function echo_debug(string $message) {
        if (defined('DEBUG') && DEBUG === true) {
            echo $message;
        }
    }    
    ?>
    
    点赞 评论 复制链接分享