在PHP 5.3.0中将视图文件包含在同一名称空间中 [英] Include view file within same namespace in PHP 5.3.0

查看:200
本文介绍了在PHP 5.3.0中将视图文件包含在同一名称空间中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在PHP5.3.0上为static关键字开发一种mvc framweork,但是因为我在这里我说我也应该利用名称空间。

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');

现在让我们说我的view.php看起来像这样:

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

<?= helper() ?>

它不起作用,因为包含的文件出于某种原因在全局命名空间中,所以我' d必须在视图中写入view \ 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.

请注意我不需要这个EXACT的解决方案代码场景,它简化了你理解我的问题。

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

推荐答案

我必须承认我还没有学习PHP的命名空间功能详细,但我不相信这是可能的。除非您声明 view.php 位于同一名称空间中,否则 included()文件将位于全局名称空间中:

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 

注意导入 helper 使用使用view \ helper; 也不可能只导入类名和其他名称空间的作品。

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

编辑:从函数中调用 include()仍然会将当前范围导出到包含的文件中,因此您可以执行以下操作:

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();

这篇关于在PHP 5.3.0中将视图文件包含在同一名称空间中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆