## The dir Function

The options that we’ve discussed so far allow you to read directory contents in a procedural way. In this section, we’ll see how you can use the dir function, which is an object-oriented mechanism for reading a directory.

When you use the dir function, and pass a directory path in the first argument, it returns an instance of the Directory class, which you can use subsequently to read the directory contents.

Let’s go through the following example to see how it works exactly.

First, we used the dir function to initialize an instance of the Directory class into the \$objDir variable. Next, we used the read method of the Directory class to iterate over all the entries.

## The FilesystemIterator Class

In this section, we’ll see how you can use the FilesystemIterator class to read directory contents. The benefit of using the FilesystemIterator class is that you can extend the methods of this class, and it also provides a lot of other useful methods that allow you to fetch various information about the files.

Let’s go through the following example to understand how it works.

As you can see, it’s really easy to use the FilesystemIterator class and iterate over the entries. In the above example, we’ve used the getFileName method of the FilesystemIterator class to get the file name. However, the FilesystemIterator class also provides several utility methods like getExtension, getSize, getPathname, and so on.

So that’s how you can use the FilesystemIterator class to get a list of files in a directory.

## Conclusion

Today, we discussed different ways of listing all the files in a directory in PHP. Here's a table to compare each method to help you choose which one is right for you.

Function or Class Notes
opendir, readdir and closedir functions not the simplest or most feature-rich method
scandir function simplest way to read a file list
glob function very simple and allows pattern matching
dir function object-oriented version of readdir
FilesystemIterator class can provide other info about files, like size or permissions