Jump to content

parent::__construct() How it works?


cutepraba

Recommended Posts

I am using parent::__construct() in almost every classes to connect Mysql DB.

Example class

class secondClass extends dbconnect
{
      public function __construct() {
        parent::__construct();

dbconnect class

class dbconnect {
	private $mysqli_handler;
	
	public function __construct() {
		try {
			mysqli_report(MYSQLI_REPORT_STRICT);
			$this->mysqli_handler = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DBNAME);
		} catch (mysqli_sql_exception $e) {
			throw new Exception('Error: Could not make a database link using ' . DB_USERNAME . '@' . DB_HOSTNAME . '!');
		}

		if ($this->mysqli_handler->connect_error) {
			trigger_error('Error: Could not make a database link (' . $this->mysqli_handler->connect_errno . ') ' . $this->mysqli_handler->connect_error);
		}
			
		$this->mysqli_handler->query("SET NAMES 'utf8'");
		$this->mysqli_handler->query("SET CHARACTER SET utf8");
		$this->mysqli_handler->query("SET CHARACTER_SET_CONNECTION=utf8");
		$this->mysqli_handler->query("SET SQL_MODE = ''");
		$this->mysqli_handler->query("SET time_zone = 'Asia/Kolkata'");
	}

 

 

Is this create multiple instance of mysql dbconnection? I am frequently getting mysql connection error on my shared hosting.  If so how to avoid?

I am using PHP Version 7.4.16, some detailed explanation will be useful for me as I am using like this for many projects.

 

Thank you for your time.

Prabakaran

Edited by cutepraba
Link to comment
Share on other sites

21 minutes ago, cutepraba said:

Is this create multiple instance of mysql dbconnection?

Every class you create that extends your dbconnect class will be creating it's own separate connection to the database.  If you're using several of these classes in a page load then that would mean several separate connections.

What you should do is have those classes accept an instance of your dbconnect class as a parameter to their constructor.

class secondClass {
    private $db;
    public function __construct(dbconnect $db){
        $this->db=$db;
    }
}

$db=new dbconnect();
$sc = new secondClass($db);

 

  • Like 1
Link to comment
Share on other sites

Just now, kicken said:

Every class you create that extends your dbconnect class will be creating it's own separate connection to the database.  If you're using several of these classes in a page load then that would mean several separate connections.

What you should do is have those classes accept an instance of your dbconnect class as a parameter to their constructor.

class secondClass {
    private $db;
    public function __construct(dbconnect $db){
        $this->db=$db;
    }
}

$db=new dbconnect();
$sc = new secondClass($db);

 

 

Thank you for the explanation.

I have changed my codes to

class secondclass {
	private $db;
  	public function __construct() {
        global $obj_db;
		$this->db = $obj_db;
  	}

 

public function selectDetails($id){
	$sql = 'some sql here';
	return dbconnect::query($sql)->rows; 
}
TO

public function selectDetails($id){
	$sql = 'some sql here';
	return $this->db->query($sql)->rows;
}

 

Is there anyway to retain dbconnect::query; without replacing to new?

 

 

 

Link to comment
Share on other sites

29 minutes ago, cutepraba said:

Is there anyway to retain dbconnect::query; without replacing to new?

If you're using the syntax dbconnect::query then there is no need to either pass in your dbconnect instance or extend that class because you're using the class like a singleton.  In that scenario you can just remove the constructor from your secondClass class.  Your overall code would look something like this:

class dbconnect { 
    private static $mysqli_handler;

    //Private constructor to prevent new dbconnect() 
    private function __construct(){
    }

    private static function connect(){
        //Reuse the existing connection if it exists.
        //Use self::$var to reference static variables.
        if (self::$mysqli_handler){
            return self::$mysqli_handler;
        }

        //Otherwise connect.
        try {
            mysqli_report(MYSQLI_REPORT_STRICT);
            self::$mysqli_handler = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DBNAME);
        } catch (mysqli_sql_exception $e) {
            throw new Exception('Error: Could not make a database link using ' . DB_USERNAME . '@' . DB_HOSTNAME . '!');
        }

        //Other stuff

        return self::$mysqli_handler;
    }

    public static function query($query){
        return self::connect()->query($query);
    }
}

class secondClass {
    public function selectDetails($id){
        $sql = 'some sql here';
        return dbconnect::query($sql)->rows;
    }
}

$sc = new secondClass();
$sc->selectDetails();

This type of code is not ideal as your secondClass is now directly linked with your dbconnect class, but it's fine for small/simple projects. Passing in your connect and updating the code to reference the provided connection is better as it allows you to provide alternative connections (such as a mock connection for testing).

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.