简体   繁体   English

将对象分配给静态变量

[英]Assigning an object to static variable

What i'm Doing Wrong 我在做什么错

class db
{

     static $dbintance=null;    


     public function __construct()
     {


       try
       {
       self::$dbintance=new PDO("mysql:host=host;dbname=dbname",user,password);
       }
       catch( PDOException $e)
       {
       die( '<b>Errors:</b> '.$e->getMessage());
       }

       }


     public static function isRecord($q)
       {

    $r=self::$dbintance->query($q)->fetch(PDO::FETCH_NUM);
    if($r[0]) return true; 
    if(!$r[0]) return false;
   }  

}

Usage 用法

 echo (db::isRecord("SELECT * FROM whcentral1 WHERE ItemDesc='ff'"))?'Yes':'NO';

Error 错误

Call to a member function query() on a non-object 在非对象上调用成员函数query()

PHP doesn't do static constructors. PHP不执行静态构造函数。 The way you've written this, you'd actually have to run new db() before it would work. 编写此代码的方式实际上必须先运行new db()才能起作用。 You might be better off using a static accessor method, eg: 使用静态访问器方法可能会更好,例如:

class db {

 static $dbintance=null;    


 public static function getConnection(){
   if (!self::$dbinstance) {
     try {
         self::$dbintance=new PDO("mysql:host=host;dbname=dbname",user,password);
     } catch( PDOException $e) {
         die( '<b>Errors:</b> '.$e->getMessage());
     }

  }
  return self::$dbinstance;
// etc.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM