duanfu1942 2014-09-07 18:08 采纳率: 100%
浏览 30

PHP OOP连接

Hey all attempting to create a small MVC kind of application. Currently working on database class.

I am running a connection to the database every time i call a functions however failing to connect successfully and being able to send the $con variable to the other functions to do whatever with.

class DB {

function __construct() {

 $con = mysqli_connect("localhost","c3337015","c3337015");

 if (mysqli_connect_errno())
  {
  return false;

  }else{

  return $con;
 }

 }



function getAll(){

if(isset($con)){

echo "Connection Successful";
echo "Do MYSQLI stuff   $con = new mysqli etc etc etc";

}else{
echo "Connection Failed";
echo "Leave me alone";
}
}
}

echo $get = DB::getAll();
  • 写回答

1条回答 默认 最新

  • douwei9973 2014-09-07 18:13
    关注

    First of all. See what is SINGLETON (it`s ideal thing for DB connection). Declare variable with connection and write singleton :) Example of singleton:

    final class Singleton
    {
        /**
         * class instance
         *
         * @var object
         * @access private
         */
        private static $oInstance = false;
        private $_db;
    
        /**
         * get instance
         *
         * @return Singleton
         * @access public
         * @static
         */
        public static function getInstance()
        {
            if( self::$oInstance == false )
            {
                self::$oInstance = new Singleton();
            }
            return self::$oInstance;
        }
    
        private function __construct() {}
    }
    

    So declare Your connection, declare method that will allow You to get connection and all done

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测