How can the concept of Inversion of Control be implemented in PHP classes for better testability and modularity?

Inversion of Control (IoC) can be implemented in PHP classes by using dependency injection. This means that instead of a class creating its dependencies internally, they are passed in from the outside. This allows for better testability as dependencies can be easily mocked or replaced with test doubles. It also improves modularity as classes are no longer tightly coupled to their dependencies.

// Example of implementing Inversion of Control using dependency injection in PHP

class Database {
    public function save($data) {
        // Save data to the database
    }
}

class UserService {
    private $database;

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

    public function createUser($userData) {
        // Business logic to create a user
        $this->database->save($userData);
    }
}

// Usage
$database = new Database();
$userService = new UserService($database);
$userService->createUser($userData);