How to use namespaces in PHP at a glance
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 .
Latest articles
- 03.04.24IT / Уроки PHP Уроки простыми словами. Урок 3. Все операторы PHP с примерами, с выводом работы кода на экран.
- 02.04.24IT / Уроки PHP Уроки простыми словами. Урок 2. Типы данных в PHP с примерами.
- 02.04.24IT / Уроки PHP Уроки простыми словами. Урок 1. Коротко о языке веб-программирования PHP. Основы синтаксиса.
- 09.11.23IT / Database Errors when migrating from MySQL 5.6 to 5.7 and how to fix them - database dump import failed with an error or INSERT does not work. Disabling STRICT_TRANS_TABLES strict mode or using IGNORE
- 08.07.22IT / Misc Convert office files DOC, DOCX, DOCM, RTF to DOCX, DOCM, DOC, RTF, PDF, HTML, XML, TXT formats without loss and markup changes