How can the combination of loading all data and lazy loading specific attributes in PHP classes improve performance in a database-driven application?

When working with database-driven applications in PHP, loading all data at once can lead to unnecessary overhead if not all attributes are needed. By lazy loading specific attributes only when they are requested, we can improve performance by reducing the amount of data fetched from the database.

class User {
    private $id;
    private $username;
    private $email;
    private $loadedAttributes = [];

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

    public function lazyLoad($attribute) {
        if (!in_array($attribute, $this->loadedAttributes)) {
            // Fetch only the requested attribute from the database
            // and assign it to the corresponding property
            $this->$attribute = fetchFromDatabase($this->id, $attribute);
            $this->loadedAttributes[] = $attribute;
        }
    }

    public function getUsername() {
        $this->lazyLoad('username');
        return $this->username;
    }

    public function getEmail() {
        $this->lazyLoad('email');
        return $this->email;
    }
}