Namespace PHP: example. How to use namespaces in PHP?

A variable defines a value, but can be a reference to another variable and have its value. During the execution of an algorithm, a variable usually takes many different values. A constant stores only one value. An object is unpredictable: it tends to have a structure, content, and many features.

php namespace

A namespace is a collection of variables, constants, objects, functions, and other constructions created by a developer that can be referenced through the name of this namespace.

Names: scope of data and algorithms

The names of elements (variables, constants, objects, functions, and other constructions of the developer) never intersect. PHP interprets any coincidence of names as a serious mistake, and in cases where it cannot unambiguously identify the problem, the developer receives code that does not work as intended, or a white field in the browser.

All names of all data must be unique, because the space is global. The names of objects and functions should also not be repeated, but the scope of global visibility is interrupted in the bodies of methods of objects and functions. Here, its own, local namespace functions and nothing prevents you from naming something inside as it is indicated outside.

Variable example, namespace analogy

The above example is a classic, if you do not pay attention to the keyword namespace: everything, as always. The second include works. The prefix NameSpaceTwo \ before the function names specifies which insertion the code is taken from.

If we remove the global keyword from the first function and the operation $ iExt = 1; transfer to the line above, then neither the first function nor the second will know about the value of the variable 100.

Namespaces: Many Descriptive Areas

In the example shown, there is a shared file that uses two inserts. Each insert has the same scCheckName () function. Which one to choose, the programmer decides, using the name of the space that is relevant at the right time in the right place in the code.

The fact that the same name is present in the common code (after merging the inserts) does not lead to an error for the simple reason that each insert file is marked with its own unique name.

In the first file, everything that will be described in it is associated with the name NameSpaceOne. In the second file, all descriptions will be attached to the name NameSpaceTwo.

Any duplication of names in both files is allowed, but in each of them any name of the element (variable, constant, object, function) must be unique.

Namespace Replacement
Namespace Replacement

In this example, changing the namespace name in the scCheckName () function call saved the $ iExt variable of the second namespace from the change. That is why the word “changed” is specially highlighted in the example - the change did not actually take place. The value of the variable remains the same.

Testing and multiple design

These simple examples show: you can easily simplify the development of complex projects, increase efficiency, productivity and speed up work. Definitely, the first ideas for using the namespace immediately appeared:

  • safe testing of scripts - by replacing "work" spaces with test counterparts;
  • safe design by large teams of developers - by providing them with "individual" spaces for describing elements.

In fact, the namespace is much more important. The PHP language, the namespace, and each description element (variable, constant, object ...) have long provided the developer with the ability to independently manipulate syntax and semantics.

keyword

Language constructions and the general rule of modern programming: "understood" - executed - there is a contradiction - the "white screen" does not work on a professional developer.

Many programmers do not even know in what place to look for a PHP error message when there is nothing in the browser (pure white field). At a certain stage of its development, the programmer thinks with the syntax and semantics of PHP, “works” automatically, and the result: its own syntax and its own semantics are allowed.

The white screen is immediately an unambiguous reaction of a professional programmer and the error is eliminated. Why waste time debugging and viewing the error log?

Objects, Arrays, and Namespaces

We can say that variables, constants and functions are the last century, but they are used in the development of objects. Good code is when the algorithm is represented by interacting objects, and not by a sequence of correct constructions.

php namespace autoload

If you use arrays of objects, manipulate the idea of ​​the stack and the last (first) element of the array, you can get the dynamics: the objects themselves “decide” how the site’s functionality should work, depending on the situation.

In PHP, a namespace is a special kind of variable, represented by its own unique name, often difficult to compose. The namespace name is used in the code. If this is a string, then one space can be replaced with another during the execution of the script.

If PHP uses namesspacespace as variable values, then this is even more semantically loaded syntax, even more powerful than arrays of objects.

An object is a structure and content that are characterized by unity. A namespace is a set of objects, elements, and relationships between them.

global space

It is impossible to conduct experiments on a working system, but thanks to namespace PHP provides the ability to simulate a real working system in another space for the following purposes:

  • further development;
  • testing;
  • maintenance, etc.

If we ignore the syntax proposed by the PHP developers and present namespaces as global complex systems of objects, then the horizons of possibilities expand many times.

Syntax and Application of the Namespace

The word namespace PHP only accepts in the first line of code for each file. All descriptions should go only after him. The syntax includes only the name indicated in the usual sense of the name.

It is essential to use the right words that reflect the meaning. It is better when the name is long, but it has something that gives a clear understanding of what kind of space is involved, what it does, what describes what it accepts or what it is created for.

Spaces can be nested into each other indefinitely, but this should not be abused. The name must be understandable, nesting is justified, and the sequence of space names must have logic.

In use and namespace applications, PHP allows for complex coding, but whenever you can, it’s better to get around a simple option.

php autoload classes namespace

General rule: namespace is a description and this is a single file, use is the import of space into the usage script and assigning it an alias (short link).

A simple example of autoload classes (objects)

The task has an object for manipulating strings, page styles (CSS descriptions), a date, file system, and database object. The point of implementation is to create simple interfaces for these five positions in order to use the necessary capabilities only through the methods of these objects.

No direct use of language features and constructions is allowed. This task uses class autoload in PHP. Namespace is considered as a collection of objects located in a specific place of the file system. Usually, all objects are placed in the file system by sense, in folders and in files with a specific name.

Startup classes (objects)

The code on the left indicates the creation of the necessary five objects, but where exactly they are located is not indicated. The code on the right shows the autoloader text (the main script), which when loading classes (objects) automatically substitutes the desired path to the location of the object and the .php file extension.

Example of many namespaces

The PhpOffice / PhpWord library is a good example of using a complex hierarchy of multiple namespaces. The elements folder contains almost the entire range of elements available when creating the * .docx (MS Word) document, other folders contain the necessary tools for working with elements, paragraphs and tables.

php namespace use

Actually, the library is placed in the project folder for the reason that the PhpOffice / PhpWord functionality space was required to be supplemented with specific tools and, ultimately, to create your own version of a similar product.

Loading many classes of different namespaces

The use of PHP namespace autoload, when it is necessary to load many classes, and the hierarchy of the developed system of objects is quite complicated and difficult to imagine, leads to the need to create rigid constructions.

Orientation of the developer (using the product to continue work) is possible only in the context of semantics (understanding of the project), which is represented by appropriate combinations of words that reflect the real meaning and relationship of objects.

main script

The need to use the library in an individual project leads to a solution to the problem of how to combine the namespaces of the developer and authors of PhpOffice / PhpWord. The best is to place this product (its spaces and objects) in its own project space.

It is important to note that without modifying the namespaces of this product at the level of its abstract elements and loading classes, you will not be able to do. This suggests that in PHP namespace, the use of internal namespaces may not be sufficiently abstract and universal.

File System and Space Localization

Essentially, namespaces are the "tracing" of the path in the file system to the desired object. Using file names as object names is natural and familiar. Using folder names as naming namespaces is objective.

The “wooden” organization of information is rather cumbersome to use and complicates the development, but it is a natural representation for systems of objects.

The problem is that the development phase is represented by a specific code editor that combines the visible presentation of folders and the contents of a specific folder, but there is no editor that provides end-to-end movement of objects and folders.

The problem of abstractness and universality

Accepted by the consciousness of the developer and objectively in reality:

  • object-oriented programming (OOP) gives abstraction and the ability to manipulate information according to its real semantics;
  • namespaces reflect the position of scripts, objects, and partly the meaning of the project in the file system

In fact, by combining the OOP abstraction on the names of objects (files) and superimposing it on the file system (folders) with adequate generation of namespace names (paths + names), you can control the formation of namespaces during script execution.

Programming has already gained powerful development dynamics, but if you transfer the process and workload of the development stage from a text editor (in which scripts are created and placed on folder trees) to the idea of ​​creating such code that allows itself to be improved and placed in the right place of the file system - programming will rise to a new height.

Source: https://habr.com/ru/post/K10670/


All Articles