Search code examples
phpspl

Why use clone keyword here


I am watching a tutorial of SPL and here is the code that confuses me

<?php

$directory = new DirectoryIterator('common/images');

foreach ($directory as $file)
{
    if($file->isFile())
        $files[] = clone $file;
}

echo $files[1]->getFileName();

If i don't use clone keyword in the foreach loop, I am not able to see the filename. Why is that so when i am pushing the whole object inside the $files array.

Thanks

Updated Part

While the above code i have to used the clone keyword. Based on the answer below that we are using clone to create a copy of object not reference. That doesn't seems to be a valid reason in this case. Consider the following example which does not need clone keyword and is working as expected

<?php

$filesystem = new FilesystemIterator('common/images');
foreach ($filesystem as $file)
{
    $files[] = $file;
}

echo $files[0]->getFileName();

Solution

  • Since php5, operator = creates reference to object, so without clone you will put pointer/reference to variable $file into array.

    But this variable is used only within loop and will/could be destroyed after foreach, because it out of the scope.

    This is why you need to create copy of it to put into array and have access to it after loop.

    UPDATE: Actually the difference a little bit deeper in this case, check out this article. DirectoryIterator returns the same object, this is why you have to clone (with its current) state during iteration, but FilesystemIterator returns new object, which can be put into array without clone.