Search code examples
phpnamespacesiteratorstandard-libraryspl

Using RecursiveIteratorIterator with namespaces?


My problem is that when I'm using namespaces, I can't use the RecursiveIteratorIterator Class of the Standard PHP Library. The following code :

<?php namespace mynamespace;

    $arr = Array("abc", Array("def", "ghi", Array("jkl")));
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
    $result = iterator_to_array($it, false);

?>

Returns:

PHP Fatal error: Uncaught Error: Class 'mynamespace\RecursiveIteratorIterator' not found in ...


Solution

  • You need to reference the global namespace with \:

    $it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));
    

    Or you can import them into the current namespace with use:

    namespace mynamespace;
    use RecursiveIteratorIterator;
    use RecursiveArrayIterator;
    

    See Using namespaces: Basics for details.