简体   繁体   中英

Mysqli: __construct() returns NULL

So I have a DB set up and I'm using a class to connect to it that extends Mysqli. Here are the relevant lines of code:

class Db extends Mysqli {
  public $result = Array();

  function __construct() {
    parent::__construct(DB_HOST, DB_USER, DB_PASS, DB_DB);
  }

I've checked the connection info, and it works fine with the mysql_connect() function.

My PHP version is 5.3, and I'm using MAMP 1.9.5 to run the environment.

So on to the issue I'm having - if I var_dump() the connection, it returns as NULL. Not false, but null. Now I've checked the specs and, just like it's predecessor mysql_connect() , it is supposed to return false in case of the connection failing. So what possible circumstance would return false?

You are not showing the complete code. This is what you have done:

class Db extends Mysqli {
    function __construct() {
       $r =  parent::__construct(DB_HOST, DB_USER, DB_PASS, DB_DB);
       var_dump($r);
    }
}

And naturally this returns NULL . The parent constructor never returns anything. Constructers are not supposed to return anything. They fill up the freshly created object instance.

You will find the connection handle and other properties in the returned object, after your constructor is done.

I'm guessing it's because of your capitalization. Extending the nonexistent class Mysqli works, and its nonexistent method connect() seems to return NULL

class Db extends Mysqli

Should be

class Db extends mysqli

@Michael is likely right about the spelling issue, but there's another issue here:

Why are you not using PDO ? PDO is installed by default on PHP 5.1 and newer.

PDO abstracts the database layer so you can write code against any database that supports PDO without having to make majorchanges.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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