我有不同的类(每个类都有自己的文件)然后有配置文件包含PDO对象和所有类对象.我正确地做了或者有更好的做法.
classA.php
class classA {
private $PDO;
function __construct($PDO) {
$this->PDO = $PDO;
}
//other functions
}
classB.php
class classB {
private $PDO;
function __construct($PDO) {
$this->PDO = $PDO;
}
//other functions
}
classC.php
class classC {
private $PDO;
function __construct($PDO) {
$this->PDO = $PDO;
}
//other functions
}
在config.php页面中:
include_once("db.php"); //contains db variables values
try
{
$PDO = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect database: " . $ex->getMessage());
}
require 'classA.php';
require 'classB.php';
require 'classC.php';
$objA = new classA($PDO);
$objB = new classB($PDO);
$objC = new classC($PDO);
几乎每个页面都包含config.php.
解决方法:
简短:是的,这是正确的,但并不完美.
但是你的代码有重复(DRY!).您可以使用继承来避免它.
也.如果你只想“死”,就不要捕捉异常.
include config.php on almost every page.
标签:php,mysql,pdo,connection
来源: https://codeday.me/bug/20190703/1367389.html