Reputation: 4772
There are lots of articles that describe how to use namespaces in PHP-5.3+ I am particularly interested in the conventions in the use
statement.
What most articles dot not point out, is that use
can reference a namespace or a class. So to reference my class in PSR-0 location Foobar/Helper/Helper.php I can either do this:
use \Foobar\Helper; // This is a namespace
class Whatever {
...
Helper\Helper::MyHelperMethod();
or this:
use \Foobar\Helper\Helper; // This is a class
class Whatever {
...
Helper::MyHelperMethod();
No packages I have seen document which they are using on each use
statement, and that can often lead to guesswork.
So, is it bad practice to use one approach or the other? Or perhaps to mix the concepts? Or is it perhaps just one of those things people rarely document?
Or maybe I am just misunderstanding the whole issue?
Upvotes: 3
Views: 722
Reputation: 31665
If you have a namespace \Foobar\Helper
, then
use \Foobar\Helper;
allows you to access all classes from the \Foobar\Helper
namespace with Helper
as a namespace qualifier. The line
use \Foobar\Helper\Helper;
gives you more control over what classes you want to access without the namespace qualifier. On the other hand, it is quite tedious to keep the use
declarations in sync with the code during development. On the third hand, it servers as a documentation about what dependencies exist in the file.
To distinguish whether a use
statement refers to a namespace or a class, an IDE such as Eclipse PDT helps.
Upvotes: 3
Reputation: 522210
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.
Upvotes: 2