包含文件中的名称空间声明是否自动包含父文件的名称空间(PHP)? [英] Do namespace declarations within included files automatically include the parent file's namespace (PHP)?

查看:76
本文介绍了包含文件中的名称空间声明是否自动包含父文件的名称空间(PHP)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该是一个简单的问题.我尚未安装5.3,所以我无法自己进行实验.

Should be a simple question. I do not yet have 5.3 installed, so I cannot experiment myself.

在包含文件中声明名称空间时,我是否必须声明名称空间的完整路径,还是已经假定要包含父名称空间?

When declaring a namespace in an included file, do I have to declare the full path of the namespace, or is the parent namespace already assumed to be included?

例如,如果我有一个文件:

For instance, if I have a file:

// file1.php
<?php
    namespace parent_space;
    include 'file2.php';
?>

和第二个文件:

// file2.php
<?php
    namespace child_space;
    // some code
?>

因为file2.php是从file1.phpparent_space命名空间中包含的,所以它是某些代码" \parent_space\child_space\的命名空间,还是仅仅是\child_space\?

Since file2.php is included from within the parent_space namespace in file1.php, is the namespace for "some code" \parent_space\child_space\ , or is it just \child_space\ ?

推荐答案

否.当包含PHP时,PHP不会对文件的位置赋予任何意义,但是在解析代码时,只要涉及名称空间,PHP便会将每个文件视为一个完全独立的实体.

No. PHP does not attach any significance to the location of your file when including, but it does treat each file as a completely separate entity as far as namespaces are concerned when parsing the code.

因此此代码将不起作用:

So this code will not work:

<?php
    namespace Food; //this is a top level namespace
    include 'file2.php';

//file2.php
<?php
    namespace Tacos; //this is still a top level namespace

您需要以这种方式定义file2.php:

You would need to define your file2.php in this manner:

<?php

namespace Food\Tacos;

有关名称空间的更多信息,请参考PHP手册: http://www.php.net/manual/en/language.namespaces.basics.php

Reference the PHP manual for more information about namespaces: http://www.php.net/manual/en/language.namespaces.basics.php

这篇关于包含文件中的名称空间声明是否自动包含父文件的名称空间(PHP)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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