Namespaces

Just a virtual directory trick

Namespaces are used throughout numerous programming languages. If you’re familiar with Java, you might have heard of the term package. A package is a namespace in Java. The package allows the developer to group similar code together. In the simplest sense, a package is a folder or a directory.

https://blog.devgenius.io/php-p67-parent-constructor-ec8e41b9a6a9

Namespaces give the programmer the ability to reuse class names in different contexts. The easiest way to look at namespaces from a non-programming perspective is through the convention on how people are named. My parents gave me the first name Dino.

Although there are probably thousands of Dino’s in the world, what defines me as part of my family’s namespace is the last name Cajic. So how does this translate to programming and PHP?

You can have two files with the same name, but they cannot be in the same directory. Why would you even care about this? You could just avoid placing files with the same name or same class name in the same directory.

If you work on larger projects where you get 3rd party code, there’s a good chance that you’re going to have some naming conflict. How do you solve this? Do you create separate directories for everything and place files into those directories like that?

What if you have frameworks that demand that you place specific types of code into specific directories? What if you’re autoloading your classes? Namespaces solve this with virtual directories. You can have two files, with exactly the same class name, but with different virtual directories, and PHP will treat them separately.

We will be looking at defining namespaces, and sub-namespaces in the next couple of articles.

Parent Constructor

PASSING DOWN CONSTRUCTOR LEGACIES FROM ANCESTORS

PHP – P67:PARENT CONSTRUCTOR

f the child class does not define a constructor, it inherits the parent constructor like any other method. If a child class defines a constructor of its own, the parent constructor will be overridden.

Namespaces

Just a virtual directory trick

PHP – P68:namespaces

Namespaces are used throughout numerous programming languages. If you’re familiar with Java, you might have heard of the term package. Similar but different.

DIVIDING AND CONQUERING THROUGH NAMESPACE ARCHITECTURE

PHP – P69:DEFINING NAMESPACES

Defining namespaces is pretty simple. At the top of the file, right after the opening PHP tag, the namespace keyword is used, followed by the virtual directory of your choosing.

Leave a Reply