PHP Singleton PDO

后端 未结 5 1555
臣服心动
臣服心动 2021-02-09 08:45

from http://www.php.net/manual/en/class.pdo.php

###### config.ini ######
db_driver=mysql
db_user=root
db_password=924892xp

[dsn]
host=localhost
port=3306
dbname         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-09 09:22

    Singleton means, that you have this class that will only have one object associated to it. So, this class will be only instantiated one single time, after that you will call a method with a name like getInstance() that will return your instance.

    Static, means that to access that method or property you don't need and instance of that object, you can call that method directly with its class class::myMethod()

    __callStatic is the way you access those static method. Is one of PHP magic-methods and is similar to __call with the difference I've just mentioned.

    For the last question, That class only gets one connection to the database. If you add another method for example, executeSelect($sql) you will have something like:

    public static function executeSelect($sql)
    {
      if (self::$link)
      {
              self::getLink()
      } 
          // execute your query here...
      return null;
    }
    

    You will only need to call it like: Database::executeSelect($sql); and it will never get two connection to the DB simultaneously.

提交回复
热议问题