Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I use a static method in PHP to create a connection to a database will I end up with one or many connections? [duplicate]

I am looking at creating an object that is called upon to pass data to the data store. My implementation uses MySQLi, but I want to allow other developers to use whatever data store they want.

I was thinking that a static method might be the best answer, but not having any familiarity with them I am unsure if I would be actually creating lots of connections or reusing the same one.

<?php
    class RECORDS {

        protected $conn;

        public function __construct() {
            //contect to DB
            $conn = $this::connection();
        }

        public static function &connection(){
            $conn = NULL;
            if($conn==NULL){
                $conn = new mysqli(_DB_HOST_, _DB_USER_, _DB_PASS_, _DB_HOST_);
                if ($mysqli->connect_errno) {
                    die("Failed to connect to MySQL: (" .
                         $mysqli->connect_errno . ") " .
                         $mysqli->connect_error);
                }
            }
            return $conn;
        }
        // ... methods that do stuff
    }

Have I got the right idea about static methods and will I be reusing the same connection or making new ones?

like image 560
Matthew Brown aka Lord Matt Avatar asked Mar 22 '15 18:03

Matthew Brown aka Lord Matt


1 Answers

Your protected $conn field is not a static field, so it is not accessible from a static method (see http://php.net/manual/en/language.oop5.static.php).

You should also use self::$conn to access a static field, or $this->conn to access object fields. The way you do it, you use a local variable making your protected $conn unused. I suppose your code should look like this:

<?php
    class RECORDS {

        protected static $conn = null;

        public function __construct() {

            //Connect to database
            self::$conn = $this::connection();
        }

        public static function &connection(){

            if(self::$conn==NULL){
                self::$conn = new mysqli(_DB_HOST_, _DB_USER_, _DB_PASS_, _DB_HOST_);
                if ($mysqli->connect_errno) {
                    die("Failed to connect to MySQL: (" .
                         $mysqli->connect_errno . ") " .
                         $mysqli->connect_error);
                }
            }
            return self::$conn;
        }
        // ... methods that do stuff
    }
like image 70
jfhs Avatar answered Oct 23 '22 12:10

jfhs