What is the correct way to access a database handle in a child class in PHP?
When working with database connections in PHP, it is important to ensure that database handles are properly accessed in child classes that inherit from a parent class. To access a database handle in a child class, you can pass the database handle as a parameter to the child class constructor or set it as a property of the child class. This allows the child class to use the database handle without needing to create a new connection.
<?php
class ParentClass {
protected $db;
public function __construct($db) {
$this->db = $db;
}
}
class ChildClass extends ParentClass {
public function __construct($db) {
parent::__construct($db);
}
public function fetchData() {
// Use $this->db to access the database handle
$result = $this->db->query("SELECT * FROM table");
// Process the query result
}
}
// Create a database connection
$db = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
// Pass the database handle to the child class
$child = new ChildClass($db);
// Access the database handle in the child class
$child->fetchData();
?>