Using public static function in mysqli functions

721 views Asked by At

I am creating a site which connects to database using public static function. As it is called by class name i can't understand how will i 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?

1

There are 1 answers

1
Catharsis On

I think what your trying to do is 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 that helps