__toString() must not throw an exception

7k views Asked by At

when i go to the browser at index.php, i get the following error Fatal error: Method MyDirectoryIterator::__toString() must not throw an exception in /home/oussama/Desktop/CoursesTraining/OOPInPHP/index.php on line 0

when i try to catch the exception, i get the same error, so how am i supposed to know what the exception is?

my home directory contains two files index.php and MyDirectoryIterator.inc.php, am using composer to handle autoload, and this is the source content:

index.php

<?php

require_once './vendor/autoload.php';


$files = new MyDirectoryIterator('../');
echo $files;

MyDirectoryIterator.inc.php

<?php


class MyDirectoryIterator {

    protected $_path;
    protected $_files;
    protected $_rfiles;

    function __construct($path)
    {
        $this->_path = __DIR__ . '/' . $path;
        $this->_files = new RecursiveDirectoryIterator($path);
        $this->_files->setFlags(
            FileSystemIterator::UNIX_PATHS |
            FileSystemIterator::SKIP_DOTS
        );

        $this->_rfiles = new RecursiveIteratorIterator($this->_files);
    }

    function __toString()
    {
        $output = '';

        foreach($this->_rfiles as $file)
        {
            $output .= $file . '<br />';
        }

        return $output;
    }
}

when i copy the content of __toString, to __construct, the code behave as expected. so why i get that error, when i execute echo $files from my index.php?

any ideas.

1

There are 1 answers

0
Oussama Elgoumri On BEST ANSWER

this is how i solve it in case someone have the same probleme:

the exception was due to permission denied, to access some files in the listing, so i just add a try catch block inside __toString method.

function __toString()
{
    $output = '';
    try {    
        foreach($this->_rfiles as $file)
        {
            $output .= $file . '<br />';
        }
    }
    catch(Exception $e) {}
    return $output;
}

the weird thing i've noticied, why that exception did not thrown when i remove __toString() from the class and i add its logic into the constructor? all the files are listed, with no exception ?