Ben
Ben

Reputation: 62394

What's the benefit of namespaces in PHP?

What's the benefit of namespaces in PHP? I've worked on multiple MVC systems and haven't found much use for them. I'm reading about them here.... is it a problem of sorts that I've never used them? Is it the kind of thing that is a good coding standard to always use?

Upvotes: 16

Views: 6354

Answers (6)

user1836049
user1836049

Reputation:

It also help your code more flexible and clear. In comparing, Zend_Database_Adapter_Mysql vs Zend/Database/Adapter/Mysql is equal to avoid ambigious names.

 // use namespace
 use Zend/Database/Adapter/Mysql as DbAdapter;
 $dbAdapter = new DbAdapter;

 // use naming convention    
 $dbAdapter = new Zend/Database/Adapter/Mysql;

When use namespace, if adapter is changed, your code would be not modified too many. All actions are only modify 'use' command. Note that in upon example, the factory method pattern should not be cared.

Upvotes: 0

Charles
Charles

Reputation: 51411

The main advantage of namespaces doesn't usually come from your own application's code, but from third party libraries. Library maintainers can select appropriate namespaces for their own code and ensure that there are no naming conflicts with your own.

Upvotes: 8

Jean-Philippe Leclerc
Jean-Philippe Leclerc

Reputation: 6805

Namespace is part of good OOP practices. They are really usefull in big web Application because they help to avoid ambiguity between classes. This is a way to organize your application and makes it more readable.

Upvotes: 6

Alexander Gessler
Alexander Gessler

Reputation: 46607

Imagine you have a huge code base, with thousands of functions, classes and lots of third-party code. And now, two functions happen to have the same name.

That's where namespaces come in - by wrapping your code into namespaces, you can eliminate the possibility of name clashes.

Also, namespaces aid you at structuring your code - everything that belongs to a certain feature or sub-system goes into one namespace.

Upvotes: 3

mauris
mauris

Reputation: 43619

Like any other languages, namespaces allow ambigious names / classes with same name to co-exists while being in two different namespaces.

For example Table class can be referring to a table in a persistent database and a HTML table. I can put namespaces to specifically use the exact table that I want, i.e. \Model\Table and \View\Table respectively.

Upvotes: 7

Imi Borbas
Imi Borbas

Reputation: 3703

It helps you to avoid name collisions. For example, if you have two packages, and each has a class named Client (or something general like that), then it would lead to a name collision. Before PHP 5.3 the solution to avoid these collisions was to use class names like this: VendorName_PackageName_Classname

As you can see it's not too nice. But now with PHP 5.3 you can use namespaces to come up with cleaner class names.

Upvotes: 2

Related Questions