How can inheritance be utilized in PHP to manage error handling and data connections effectively?
Inheritance in PHP can be utilized to create a base class that handles error handling and data connections, which can then be extended by other classes that require these functionalities. By centralizing error handling and data connections in a base class, you can ensure consistency and reusability throughout your codebase.
<?php
class Database {
protected $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
$result = $this->connection->query($sql);
if (!$result) {
die("Error executing query: " . $this->connection->error);
}
return $result;
}
}
class User extends Database {
public function getUserById($id) {
$sql = "SELECT * FROM users WHERE id = $id";
$result = $this->query($sql);
return $result->fetch_assoc();
}
}
$database = new Database("localhost", "username", "password", "database");
$user = new User("localhost", "username", "password", "database");
$userData = $user->getUserById(1);
print_r($userData);
?>