views:

266

answers:

2

Hi,

I started developing sort of a mvc framweork on PHP5.3.0 for the static keyword, but since I'm here I said I should take advantage of the namespaces as well.

So I have something like this for the view:

namespace view
{
    function load($filepath)
    {
        include($filepath);
    }
    function helper()
    {
        echo 'lorem ipsum';
    }
}
view\load('view.php');

Now let's say my view.php looks like this:

<?= helper() ?>

It does not work, becuase the included file is for some reason in the global namespace, so I'd had to write view\helper() inside the view, which kind of defeats the purpose.

Do you have any idea how to accomplish this? Pretty much what the question title is, to include a file within the same namespace where the including is taking place.

Please note that I don't need solutions for this EXACT code scenario, it was simplified for you to understand my problem.

Thanks!

+3  A: 

I must admit I've yet to study PHP's namespace features in detail, but I don't believe that's possible. The included() file will be in the global namespace unless you declare that view.php is in the same namespace:

namespace view;
helper(); // works

Note that importing helper using use view\helper; is not possible either as importing only works of class names and other namespaces.

EDIT: Calling include() from within a function will still export the current scope to the included file, so you could do something like this:

namespace view {
    class Template { 
        public function load($filepath) { 
            include($filepath);
        }

        function helper(){
            echo 'lorem ipsum';
        }
    }

    $a = new Template();
    $a->load('test.php');
}

view.php:

$this->helper();
Øystein Riiser Gundersen
A: 

I'd implement autoloading classes instead of loading them with "load" method. Also I don't see why you can't put all view.php files in the same namespace.

FractalizeR