dougang1967 2017-03-06 19:09
浏览 7
已采纳

为什么外部变量超出了PHP的作用范围? [重复]

This question already has an answer here:

I have a small problem with a PHP function that can't access a variable that was defined outside its code block and I can't see what the problem is. Redefining the variable inside the function block works fine but seems a superfluous step:

<?php
    //constants for database connection
    define(DB_RESOURCE, "192.168.99.67");
    define(DB_USERNAME, "myUsername");
    define(DB_PASSWORD, "p@ssword");
    define(DB_NAME, "myDatabase");
    //variable defined here so why can't function see it?
    $dbConnect = mysqli_connect(DB_RESOURCE, DB_USERNAME, DB_PASSWORD, DB_NAME);


    function readData($table, $column) {
        $sql = "SELECT {$column} FROM {table}";
        //redefining this solves the problem but why is this needed?
        // $dbConnect = mysqli_connect(DB_URL, DB_USER, DB_PASS, DB_NAME);
        //the $dbConnect variable is not defined and error is flagged in PHPStorm in the line below
        $data =  mysqli_query($dbConnect, $sql);
    }
?>

Any ideas why this is happening?

Many thanks for your help,

Kw

</div>
  • 写回答

5条回答 默认 最新

  • douyong1285 2017-03-06 19:17
    关注

    in php if you want to use any variable inside any function without passing it in parameter. you need to defined it as global. it before using you need global $dbConnect.

    <?php
        //constants for database connection
        define(DB_RESOURCE, "192.168.99.67");
        define(DB_USERNAME, "myUsername");
        define(DB_PASSWORD, "p@ssword");
        define(DB_NAME, "myDatabase");
        //variable defined here so why can't function see it?
        $dbConnect = mysqli_connect(DB_RESOURCE, DB_USERNAME, DB_PASSWORD, DB_NAME);
    
    
        function readData($table, $column) {
            $sql = "SELECT {$column} FROM {table}";
            //redefining this solves the problem but why is this needed?
            global  $dbConnect;
            // now you can use $dbConnect. In php you need to specify it as global once inside the block after it you can use 
    
            $data =  mysqli_query($dbConnect, $sql);
        }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗