What are the best practices for handling object instantiation and variable access in PHP scripts to avoid redundancy and improve code organization?

To avoid redundancy and improve code organization in PHP scripts, it's best to follow the principle of Don't Repeat Yourself (DRY) by centralizing object instantiation and variable access. One way to achieve this is by using dependency injection to pass objects as parameters to functions or classes, rather than instantiating them within the function or class itself. This approach promotes code reusability, testability, and maintainability.

// Example of using dependency injection to avoid redundancy and improve code organization

class UserService {
    private $db;

    public function __construct(Database $db) {
        $this->db = $db;
    }

    public function getUserById($userId) {
        return $this->db->query("SELECT * FROM users WHERE id = $userId");
    }
}

// Instantiate the Database object
$db = new Database();

// Instantiate the UserService object with the Database object passed as a parameter
$userService = new UserService($db);

// Access the getUserById method without redundant instantiation of the Database object
$user = $userService->getUserById(1);