3

有很多文章描述了如何在 PHP-5.3+ 中使用命名空间,我对use声明中的约定特别感兴趣。

大多数文章没有指出的是,use它可以引用命名空间或类。因此,要在 PSR-0 位置 Foobar/Helper/Helper.php 中引用我的课程,我可以这样做:

use \Foobar\Helper; // This is a namespace
class Whatever {
    ...
    Helper\Helper::MyHelperMethod();

或这个:

use \Foobar\Helper\Helper; // This is a class
class Whatever {
    ...
    Helper::MyHelperMethod();

我没有看到他们在每条use语句中使用的包文件,这通常会导致猜测。

那么,使用一种方法或另一种方法是不好的做法吗?或者也许混合概念?或者它可能只是人们很少记录的那些事情之一?

或者,也许我只是误解了整个问题?

4

2 回答 2

3

如果你有一个命名空间\Foobar\Helper,那么

use \Foobar\Helper;

允许您使用命名空间限定符访问命名空间中的所有类。线\Foobar\HelperHelper

use \Foobar\Helper\Helper;

在没有命名空间限定符的情况下,您可以更好地控制要访问的类。另一方面,use在开发过程中保持声明与代码同步是相当乏味的。另一方面,它作为关于文件中存在哪些依赖项的文档提供服务。

要区分use语句是指命名空间还是类,Eclipse PDT 等 IDE 会有所帮助。

于 2013-10-27T18:10:00.973 回答
2

The point of use is to reduce repeatedly typing the same fully qualified class name. It allows you to produce shorter, more readable code. It depends on your situation which is the most readable way to write your code. If you just need one class from a namespace, you can alias it directly. If you need a lot of classes from one namespace, it may make the most sense to alias only up to the namespace. If several classes from separate namespaces are similarly named, it can make code clearer if you only alias up to the namespace. It's entirely up to you and the situation.

于 2013-10-27T18:16:12.160 回答