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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With