- 您当前的课程相当无用。如果它为PDO添加了一些额外的功能,则创建数据库包装器将是有意义的。但鉴于其当前代码,最好改用香草PDO。
- 无论哪种方式,都可以通过普通PDO或数据库类创建 单个 $ db实例。
- 将其作为构造函数参数传递给 需要数据库连接的每个类
database.php:
<?php$host = '127.0.0.1';$db = 'test';$user = 'root';$pass = '';$charset = 'utf8';$dsn = "mysql:host=$host;dbname=$db;charset=$charset";$opt = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false,];$pdo = new PDO($dsn, $user, $pass, $opt);
user.php
<?phpclass User { private $conn; public function __construct(PDO $pdo) { $this->conn = $pdo; } public function getUsers() { return $this->conn->query("SELECt username, usermail FROM user")->fetchAll(); }}
app.php
include 'database.php';$user = new User($pdo);$list = $user->getUsers();foreach($list as $test) { echo $test["username"],"n";}
输出:
username_foousername_barusername_baz
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)