Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit of namespaces in PHP?

Tags:

namespaces

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?

like image 466
Webnet Avatar asked Mar 22 '11 14:03

Webnet


People also ask

What is the purpose of namespace in PHP?

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.

What is the advantage of namespace?

The biggest advantage of using namespace is that the class names which are declared in one namespace will not clash with the same class names declared in another namespace. It is also referred as named group of classes having common features.

What is the difference between namespace and use in laravel?

The use keyword allows the developers to shorten the namespace. The namespace once created can include various functionalities which can be used in controllers and various classes.

What is namespace example?

In an operating system, an example of namespace is a directory. Each name in a directory uniquely identifies one file or subdirectory. As a rule, names in a namespace cannot have more than one meaning; that is, different meanings cannot share the same name in the same namespace.


1 Answers

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.

like image 178
mauris Avatar answered Oct 27 '22 01:10

mauris