dongye9991 2013-11-09 20:34
浏览 18
已采纳

函数:将指针传递给$ con

I'm displaying a relatively "heavy" PHP page. I have several functions that each use a connection to the DB to grab some rows. I've noticed that making a new $con in each function slows things down a lot, so naturally I would like to use the same $con for each function on the page. I tried this:

$con = mysqli_connect("localhost","root","root", "mydb");

function fA($a, $b, &$con = $con)
{}

function fB($a, &$con = $con)
{}

You can see I'm trying to pass a pointer to $con for each function, but I get a syntax error, unexpected $con for each one. (I could pass $con to the functions whenever I call them but doing it this way I don't have to go back and change every function call, and it looks neater)

  • 写回答

2条回答 默认 最新

  • dpfln86244 2013-11-09 20:36
    关注

    You can use:

    global $con;
    

    At the beginning of each function's body like so:

    function fA($a, $b) {
        global $con
        // ...etc...
    }
    

    But this is generally viewed as a bad practice.

    A better approach would be to use dependency injection so that your logic would not be dependent on the kind of storage device given to it. Something along these lines:

    class LogicExecutor {
        private $con;
    
        public __construct($con) {
            $this->con = $con;
        }
    
        public function doTaskOne($a, $b) {
            // you can use $this->con in this scope
        }
    }
    
    $con = mysqli_connect('localhost', 'root', 'root', 'mydb');
    $le = new LogicExecutor($con);
    
    $le->doTaskOne('a','b');
    

    But even that would couple your code to mysqli very tightly. Have you considered an ORM?

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

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?