开发者

Scope of a variable in PHP5 with mysqli

开发者 https://www.devze.com 2023-04-11 19:41 出处:网络
<?php class UBC_DB { private $db; public function connect() { $db = new mysqli(\'localhost\', \'root\', \'root\', \'NewsTable\');
<?php
  class UBC_DB
  {
      private $db;


   public function connect()
   {
       $db = new mysqli('localhost', 'root', 'root', 'NewsTable');
   }

   public function getDB()
   {
       if(!$db)
       {
           printf("Can't connect to MySQL Server. ErrorCode: %s\n", mysqli_connect_error());
           exit;
       }
   }
}

$api = new UBC_DB();
$api->connect();
$api->getDB();
?>

Hello, PHP masters. I've got a problem here and need your help... I'm trying to make a nice neat class to deal with DB connection... However, even if that db is connected successfully and returns the appropriate result to $db, I cannot reuse this variable in another method in the same class! shouldn't $db remember what it has received before? In getDB method开发者_开发知识库, it says $db has nothing : ( PHP has a different variable scope-rules?


The scoping rules are different than other languages like Perl, it is true.

I suggest the following singelton-style DB class:

<?php
  class UBC_DB
  {
      private static $db;


   private static function connect()
   {      
       self::$db = new mysqli('localhost', 'root', 'root', 'NewsTable');       
   }

   public static function getDB()
   {
       if(!self::$db)
       {
           self::connect();
       }
       return self::$db;
   }
}


$db = UBC_DB::getDB();
0

精彩评论

暂无评论...
验证码 换一张
取 消