0

我想做的是:

class DB extends mysqli {
 ...
}

DB :: connect( ... );

DB :: query( "SELECT * FROM myDB" );

class AnotherClass {
  function helloWorld()
  {
     DB :: query( "SELECT * FROM withoutUsingGlobalKeyword" );
  }
}

function functions()
{
    DB :: query( "SELECT * FROM withoutUsingGlobalKeyword" );
}

这个问题的重点是避免使用“全局”关键字,例如:

global $mysqli;
$mysqli = new mysqli( ... );

class AnotherClass {
   function helloWorld()
   {
      global $mysqli;
      $mysqli->query( "SELECT * FROM IDontWantToUseGlobalKeyword" );
   }
}

function functions()
{
    global $mysqli;
    $mysqli->query( "SELECT * FROM IDontWantToUseGlobalKeyword" );
}

一个解决方案是在 $_ENV 数组中声明 mysqli 变量,但我不想使用 $_ENV 来管理 MYSQLI,我想使用像 DB 这样的静态类(这可能吗?)

4

2 回答 2

0

毕竟,我找到了解决方案:

global $mysqli;
$mysqli = new mysqli( ... );

class DB  {
  public static function getConnection()
  {
     global $mysqli;
     return $mysqli;
  }
 ...
}



$mysqli->query( "SELECT * FROM myDB" );

class AnotherClass {  
  function helloWorld()
  {
     $db = DB :: getConnection();
     $db->query( "SELECT * FROM withoutUsingGlobalKeyword" );
  }
}

class DBAccess {
   public $db;
   function __construct()
   {
      $this->db = DB :: getConnection();
   }
}

class MultipleMethodDBSupport extends DBAccess {
   function __construct()
   {
       parent :: __construct();
   }

   function m1()
   {
      $this->db->query( "SELECT * FROM withoutUsingGlobalKeyword" );
   }

   function m2()
   {
      $this->db->query( "SELECT * FROM withoutUsingGlobalKeyword" );
   }
}

function functions()
{
    $db = DB :: getConnection();
    $db->query( "SELECT * FROM withoutUsingGlobalKeyword" );
}
于 2012-05-21T11:11:05.457 回答
0

这属于组合而不是继承。使用您提供的示例,将类传递给 mysql 对象会更好。

Class DB {
    protected $mysqli;
    function __construct( Mysqli $mysqli ) {
        $this->mysqli = $mysqli;
    }
    function helloWorld() {
        $this->mysqli->query( "SELECT * FROM IDontWantToUseGlobalKeyword" );
    }
}

$db = new DB( new mysqli(...) );
$db->helloWorld();

您的示例似乎不需要任何继承。

于 2012-05-21T06:11:09.277 回答