有可能从mysqli扩展到新类并将其用作静态吗?

时间:2012-05-21 05:54:19

标签: php mysql database mysqli

我想做的是:

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'关键字,如:

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这样的静态类(这可能吗?)< / p>

2 个答案:

答案 0 :(得分:0)

这属于composition over inheritance。使用您提供的示例,jsut将类传递给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();

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

答案 1 :(得分: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" );
}