What is the best method for getting a database connection/object into a function in PHP?

前端 未结 6 1652
醉梦人生
醉梦人生 2020-12-05 16:59

A couple of the options are:

$connection = {my db connection/object};

function PassedIn($connection) { ... }

function PassedByReference(&$connection) {         


        
6条回答
  •  无人及你
    2020-12-05 17:12

    function usingFunc() {
      $connection = getConnection();
      ...
    }
    
    function getConnection() {
      static $connectionObject = null;
      if ($connectionObject == null) {
        $connectionObject = connectFoo("whatever","connection","method","you","choose");
      }
      return $connectionObject;
    }
    

    This way, the static $connectionObject is preserved between getConnection calls.

提交回复
热议问题