PHP Iterator Class

I work with recursive PHP SPL iterators, they pretty confuse me, but I'm learning.

I use them in a project where I need to recursively capture all files and exclude folders from my result. At first I used this method ...

$directory = new RecursiveDirectoryIterator($path); $iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::CHILD_FIRST); foreach ($iterator as $fileinfo) { if ($fileinfo->isDir()) { //skip directories //continue; }else{ // process files } } 

But then the SO user suggested using this method instead, so that I would not need to use the isDir() method in my loop ...

 $directory = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS); $iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::LEAVES_ONLY); 

Note that I used RecursiveDirectoryIterator::SKIP_DOTS in the RecursiveDirectoryIterator constructor, which should skip folders or . and ..

Now I'm confused, because after some test, even without using RecursiveDirectoryIterator::SKIP_DOTS , it seems that it doesn’t show them, I use Windows, maybe this is the reason, only the dots are displayed only on a system like Unix? Or am I embarrassed that something is missing?

Also, using RecursiveIteratorIterator::LEAVES_ONLY instead of RecursiveIteratorIterator::CHILD_FIRST , it will stop showing folders in my result, what I want, but I don’t understand why? There is no information about this in the documentation.

+6
source share
1 answer

A sheet is an element in a tree that does not have any additional elements depending on it, i.e. this is the end of the branch. By definition, files correspond to this description.

 -- folder | |- folder | | | |- file <- a leaf | | | -- folder | | | -- file <- another leaf | -- file <- yet another leaf 

By setting RecursiveIteratorIterator to "sheet only" mode, it will skip any element that is not a sheet.

+3
source

Source: https://habr.com/ru/post/905706/


All Articles