An error message stating "Uncaught Error: Call to undefined method Database::prepare()" may arise when attempting to use a PDO connection in a separate class. This error stems from a misunderstanding of how object-oriented programming (OOP) interconnects objects.
1. Rethink Your Database Class:
The existing Database class serves no meaningful purpose. Instead, focus on creating a wrapper class if it extends PDO's functionality.
2. Establish a Central Database Connection:
Instantiate a standalone $db object using PDO or your enhanced database class. This single connection will serve as the cornerstone for all future database activities.
3. Pass the Connection as a Constructor Parameter:
Every class requiring database access should receive the $db connection as a constructor argument. This approach guarantees seamless access to the database throughout your entire application.
Consider the following improved codebase:
database.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:
class User { /* Properties */ private $conn; /* Get database access */ public function __construct(\PDO $pdo) { $this->conn = $pdo; } /* List all users */ 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"; }
This refined codebase exemplifies the correct usage of PDO connections in multiple classes, ensuring error-free operation and elegant coding practices.
The above is the detailed content of How to Properly Use a PDO Connection Across Multiple Classes in PHP?. For more information, please follow other related articles on the PHP Chinese website!