PHP Mysqli Extension Warning [closed]

2019-08-28 23:38发布

问题:

I have the following code and I can't explain why it outputs an error.

class User extends mysqli{

    // property declaration
    private $server;
    private $user;
    private $pass;
    private $database;
    private $conn;

    function __construct($server, $user, $pass, $database){

        $mysqli = new mysqli($server, $user, $pass, $database);
        if ($mysqli->connect_errno) {
            echo "Connect failed: ". $mysqli->connect_error;
            exit();
        }

        $this->conn = $mysqli;

        return 0;

    }

    function __destruct(){

        $conn = $this->conn;
        $conn->close();

    }
}

and main code

include("global_config.php");

require "User.php";

$u = new User($con['server'],$con['user'],$con['pass'],$con['db']);

$u->query("SELECT * FROM users");

returns this error

Warning: mysqli::query() [mysqli.query]: Couldn't fetch User in E:\Xampp\htdocs\testphp\testMysql.php on line 9

normally, it should behave as here PHP inheritance, parent functions using child variables

but it doesn't

i've already exhausted my imagination thinking about most possible keywords I could use for a google search

any ideas?

回答1:

First thing you are doing wrong is that your User object extends mysqli object and they dont have anything similar. Inheritance is "IS A" relationship. And for your User object to use Mysqli object you need "HAS A" relationship. This is also called composition.

And if you are using inheritance, that don't use composition since you don't need to use both really. In this case, inheritance is wrong choice.

If you want to give User object access to a database through Mysqli, you need to have Mysqli object inside your User object.

The best way to achive that is to have two objects, one would represent Mysqli, and the other one would represent User.

Your User class can look like this:

class User 
{
    private $user;
    private $pass;
    private $db;

    function __construct($db)
    {
        $this->db = $db;
    }
}

And you would use it like this:

$db = new mysqli($server, $user, $pass, $database);
$user = new User($db);

Now user has access to Mysqli object and can interact with database.

Now to go further, you can make your own little database abstraction layer that would hold both mysqli and mysqli stmt objects, and there you could have functions to do CRUD. Then you would pass that database abstraction layer object into your User object and this way you would be even more powerful.

And dont use exit() function, just use return to stop a function. I know exactly what are you going through now :) Read this article: http://phpmaster.com/liskov-substitution-principle/ and go through examples to understand why composition is better than inheritance for this.

Good luck!



标签: php oop