duanbai1974 2016-10-30 10:06
浏览 25

数据库连接构造函数:私有还是公共?

If I want to create a connection class, is it OK to have the __construct as private? Or that will prevent users from connecting if there is more than one user at a time? Or I'm doing something that's completely wrong and this connection class should not even exist? (using connection without specific class would be better?)

code:

   <?php

class Connection
{     
    private $host = "hostname";
    private $db_name = "somedatabase";
    private $username = "username";
    private $password = "";
    private $conn;

    private function __construct()
 {


        try {
        $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
            echo "Connected Successfully Bro";
        }
  catch(PDOException $exception) 
  {
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}


?>
  • 写回答

1条回答 默认 最新

  • dsd57259 2016-10-30 10:29
    关注

    If you make the constructor private, only methods within that class will be able to create an instance of it.

    That's useful if you are implementing the Singleton pattern (https://en.wikipedia.org/wiki/Singleton_pattern), or if you are creating a factory class for example.

    The code you provided shows the class not having any other methods, so a private constructor is going to render the class useless if that's the case.

    In short, if you need to instantiate the "Connection" class from code outside of the class itself, use a public constructor.

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向