繁体   English   中英

可以在新类中从mysqli扩展并将其用作静态吗?

[英]It's possible to extend from mysqli in a new class and use it as an static?

我想做的是这样的:

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

这属于继承的构成 使用您提供的示例,最好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();

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

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

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" );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM