Sign in Registration
ArticlesDownloadServicesAudioContacts
ruen

How to use namespaces in PHP at a glance

Пространства имён в PHP

The concept of a namespace has long been present in many popular programming languages. Finally, starting with version 5.3, this feature has been introduced into the PHP language.

Why use namespaces ? Using a namespace will help avoid class naming conflicts and will also allow you to more transparently see the structure of the project. By default, if you do not specify a namespace, the class will exist in the global namespace, the same thing happened when PHP did not support this functionality. Now, it is enough to write something like the following before declaring the class, and the class will already exist in the specified namespace:

  namespace my_namespace; 

Where "my_namespace" is any name, names can be like addresses, backslash \ is used to separate path parts. Once declared, you can use the class like this:

  $ object = new my_namespace \ Class (); 

Alternatively, you can specify that a specific namespace will be used so that you do not have to explicitly specify it each time an object is instantiated. This is done using the following construction:

  use my_namespace \ Class; 

If you implement a class autoloader, then it will be enough to take part of the path "my_namespace \ Class" and glue it to the other part of the path where the classes are stored. This way, autoloading of classes can be easily implemented.

For more information on namespaces that will take a while to learn, see the official PHP website at this address .

Comments (0)
For commenting sign in or register.

Latest articles

Popular sections

Communication

Login to the web version
Android app:
Available on Google Play

Share this

Subscribe to