How can the code provided be optimized or made more efficient for recursively reading directories in PHP?

The code provided can be optimized by using the DirectoryIterator class in PHP, which provides an object-oriented interface for reading directory contents. By using DirectoryIterator, we can simplify the code and improve its efficiency for recursively reading directories.

function readDirectory($path) {
    $iterator = new DirectoryIterator($path);
    
    foreach ($iterator as $item) {
        if ($item->isDot()) continue;
        
        if ($item->isDir()) {
            echo "Directory: " . $item->getPathname() . "\n";
            readDirectory($item->getPathname());
        } else {
            echo "File: " . $item->getPathname() . "\n";
        }
    }
}

// Usage
readDirectory('/path/to/directory');