Using public static function in mysqli functions
I am creating a site that connects to a database using a public static function. Since it is called by the name of the class, I cannot figure out how I will execute mysqli_query()
. Below is the code:
db.class.php
<?php
class connect
{
private static $db_host='localhost';
private static $db_user='root';
private static $db_pass='';
private static $db_name='i_constuddoer01';
//using public static function to avoid overloading
public static function cxn_mysqli() {
$result=mysqli_connect(self::$db_host,self::$db_user,self::$db_pass,self::$db_name);
if(!$result)
header("Location: sorry.php");
else
return $result;
}
}
}
functions.php
<?php
require_once('db.class.php');
function addUser($fname,$lname,$email,$pass) {
$query="INSERT INTO users VALUES(...)";
$qr_status = mysqli_query(connect::cxn_mysqli(),$query)
}
What should I do, is there any other way?
+3
source to share
1 answer
I think you are trying to create a singleton class, below is an example of one
class Connect
{
private static $instance;
# make the construct private to avoid anyone using new Connect()
private function __construct()
{
# Sql connect code in here
}
static public function i()
{
if(!is_object(self::$instance)) {
return new self;
}
return self::$instance;
}
}
# Lets try to create two instances
$i = Connect::i();
$j = Connect::i();
# Oh look they are exactly the same object
echo spl_object_hash($i)."\n";
echo spl_object_hash($j)."\n";
Hope it helps
0
source to share