如何在oops中创建连接对象以及如何在php中的另一个类中使用?

时间:2017-02-10 07:15:37

标签: php mysql oop mysqli

这是我的配置类,我想在另一个类中使用此连接。请给我建议解决这个问题或粘贴一个工作代码,以便我可以将它用于我的项目。

<?php
    /*
    * MySQLi database class - only one connection allowed
    */
    class Configuration {
        private $_connection;
        private static $_instance; //The single instance
        private $_host = "localhost";
        private $_username = "root";
        private $_password = "";
        private $_database = "centreonyx";
        /*
        Get an instance of the Database
        @return Instance
        */
        public static function getInstance() {
            if(!self::$_instance) { // If no instance then make one
                self::$_instance = new self();
            }
            return self::$_instance;
        }
        // Constructor
        private function __construct() {
            $this->_connection = new mysqli($this->_host, $this->_username, 
                $this->_password, $this->_database);

            // Error handling
            if(mysqli_connect_error()) {
                trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(),
                     E_USER_ERROR);
            }
        }
        // Magic method clone is empty to prevent duplication of connection
        private function __clone() { }
        // Get mysqli connection
        public function getConnection() {
            return $this->_connection;
        }
    }
    ?>


    this is my another class in which i want to use the connection 

    <?php 
    require_once 'Config/Configuration.php';
    class XYZ {
        public function  _construct()
        {
             $db = Configuration::getInstance();
            $this->mysqli = $db->getConnection(); 
        }
    function insertBlogDetails($bcat,$bname,$bdesc,$bdate,$bwritter)
    {
        echo $bdate;

        /*check blog exist*/
        echo $bdate."  nearc congif";   
        $sqlToCheckBlog="SELECT * FROM blog_details WHERE Blog_Name='".$bname."'";
        $resultQueryCheck=$this->mysqli->query($sqlToCheckBlog);
        print_r($resultQueryCheck);
        exit();
      }
    }
    ?>

请尽快回复我。 谢谢你提前。

0 个答案:

没有答案