多个文件和命名空间范围(Multiple Files and Namespaces Scope)

编程入门 行业动态 更新时间:2024-10-26 16:22:14
多个文件和命名空间范围(Multiple Files and Namespaces Scope)

我对命名空间很新(是的,我已经阅读了PHP文档命名空间部分)。 我想知道名称空间的范围与多个文件有关。 当我在具有全局代码的文件中包含或要求该文件时,名称空间是否有效超出一个文件? 此外,这对全局代码有何影响? 我是否会被迫使用全局代码更改语法。

例如,假设我有文件A.php。 我希望能拥有的是:

namespace A; class Abc { ... }

然后让我说我有一些带有全局代码的文件,称之为main.php:

include("A.php"); class Abc { ... } $abc = new Abc(); // Should be global Abc, right? $abcFromNameSpace = new A\Abc(); // Should be namespace Abc, right? ...

作为一个后续问题,我也想知道如果我要将带有名称空间的文件包含在具有名称空间的另一个文件中,那么在范围方面会发生什么,而不是上面的示例,其中main.php只有全局代码。 这会是这样的:

namespace A; class Abc { ... }

然后让我说我有一些带有全局代码的文件,称之为B.php:

namespace B; include("A.php"); class Abc { ... } $abc = new B\Abc(); // Should be namepsace B Abc, right? $abcFromNameSpace = new A\Abc(); // Should be namespace A Abc, right?

I'm pretty new to namespaces (and yes, I've read the PHP documentation namespaces section). I'm wondering what the scope of namespaces is with regard to multiple files. Is a namespace valid beyond one file when I include or require that file in a file that has global code? And furthermore, how does that affect the global code? Would I be forced to change anything syntax-wise with the global code.

For example, let's say I have file A.php. What I want to be able to have is this:

namespace A; class Abc { ... }

And then let's say I have some file with global code, call it main.php:

include("A.php"); class Abc { ... } $abc = new Abc(); // Should be global Abc, right? $abcFromNameSpace = new A\Abc(); // Should be namespace Abc, right? ...

As a follow-up question, I'm also wondering what would happen with regard to scope if I were to include a file with namespaces inside another file with namespaces, as opposed to the above example, where main.php only has global code. Would that work like this:

namespace A; class Abc { ... }

And then let's say I have some file with global code, call it B.php:

namespace B; include("A.php"); class Abc { ... } $abc = new B\Abc(); // Should be namepsace B Abc, right? $abcFromNameSpace = new A\Abc(); // Should be namespace A Abc, right?

最满意答案

每次引用当前文件或类范围之外的类时,都使用其命名空间:

<?php namespace B; $class = new \A\Abc();

但如果您在脚本中“使用”命名空间,则可以将其删除:

<?php namespace B; use A\Abc; $class = new Abc();

Any time you refer to a class that is outside of the current file or class scope, you use its namespace:

<?php namespace B; $class = new \A\Abc();

But if you "use" the namespace in your script, you can leave it out:'

<?php namespace B; use A\Abc; $class = new Abc();

更多推荐

本文发布于:2023-08-08 00:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466769.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   文件   空间   Multiple   Namespaces

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!