简体   繁体   English

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

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

What I want to do is this: 我想做的是这样的:

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

The point of this question is to avoid the use of the 'global' keyword like: 这个问题的重点是避免使用'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" );
}

A solution for this is to declare the mysqli variable in the $_ENV array, but I don't want to use $_ENV to manage the MYSQLI, I want to use a static class like DB (Is that possible?) 一个解决方案是在$ _ENV数组中声明mysqli变量,但是我不想使用$ _ENV来管理MYSQLI,我想使用像DB这样的静态类(可以吗?)

This falls under the composition over inheritance . 这属于继承的构成 With the example you provided it would be much better to jsut pass the class a mysql object. 使用您提供的示例,最好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();

Your examples don't seem to require any inheritance. 您的示例似乎不需要任何继承。

After of all, I found a solution: 毕竟,我找到了解决方案:

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