PHP OOP extensible class cannot access database connection

Perhaps you can help. I have a main class that creates a MySql connection. Then I extend this class. I was unable to access the connection, unless I did the parent :: __ construct (); and recently while doing this, I got an error that caused me to not connect.

So how to do it so that it doesn't end up with connections and can access the database connection.

class Common 
{
    var $mysql;

    function __construct()
    {   
        $this->mysql=new mysqli($this->dbHOST, $this->dbUSERNAME, $this->dbPASSWORD, $this->dbNAME);
    }
}

class Role extends Common {

    function __construct()
    {
        parent::__construct();
    }
}

      

+2


source to share


2 answers


I think there is a fundamental problem with your class structure: you don't need the connection to the object, you only need a copy of the connection resource to the object.

My preferred way out of this is to create a single point call database handler. Now it can be called anywhere and will always return the same connection handler. It's also a great way to hide auto-initialization.



The decision was confirmed by the fact that the class that represents the database string is actually quite different from the class that is the database connection. An application will work on many many lines, but rarely, if ever, will deal with multiple connections. Another way to do this is to distinguish between the IS-A and HAS-A definitions: it doesn't make sense to say "IS-A class database connection". It makes sense to say "HAS-A DAT class database connection".

0


source


Make sure you closed the connection when the object was destroyed. That is, add a method __destruct()

that closes the connection.



If the class Common

is the one that opens the connection in its method __construct()

, then it should close it in its method __destruct()

. If you don't define a method __destruct()

in the class Role

, then it looks like PHP won't automatically call the parent __destruct()

. (I haven't tested this.) A simple solution is to add a stub method __destruct()

that just calls parent::__destruct()

.

0


source







All Articles