Namespaces and Code Integration
Learn about the namespace, its definition, directory structure, and how to import multiple namespaces in a file.
We'll cover the following
As our projects grow in complexity, we have no choice but to integrate code from different sources. These sources can be any of the following:
- Codebases written by or contributed to by other programmers.
- Code libraries developed elsewhere that can solve our problems and save us a lot of effort in writing our own libraries and resources.
In spite of the many benefits of code integration, we might encounter some problems when we integrate code from different resources. One big problem is that of name collision, which occurs when different classes have the same name or when their methods have the same name. That problem has been solved in PHP 5.3 and onwards by the introduction of namespaces.
The directory structure
We’ll start by creating an index.php
file in the root directory of our site. Next, we’ll create a class named CarIntro
and place it in the src/Car
folder, as follows: /src/Car/CarIntro.php
.
Let’s look at the illustration below to better understand the folder structure:
Get hands-on with 1400+ tech skills courses.