What are some best practices for managing object scope and dependencies in PHP classes?
When managing object scope and dependencies in PHP classes, it is important to follow best practices to ensure clean and maintainable code. One common approach is to use dependency injection to pass dependencies into a class rather than creating them within the class itself. This helps to decouple classes and makes it easier to test and reuse code.
<?php
class Database
{
private $connection;
public function __construct($host, $username, $password, $database)
{
$this->connection = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
public function query($sql)
{
return $this->connection->query($sql);
}
}
class UserRepository
{
private $db;
public function __construct(Database $db)
{
$this->db = $db;
}
public function getUserById($id)
{
$result = $this->db->query("SELECT * FROM users WHERE id = $id");
return $result->fetch();
}
}
// Usage
$db = new Database('localhost', 'username', 'password', 'dbname');
$userRepository = new UserRepository($db);
$user = $userRepository->getUserById(1);