0
0
PHPprogramming~30 mins

Aliasing with as keyword in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Aliasing with as keyword in PHP
📖 Scenario: Imagine you are organizing a small library system. You have two classes named Book and Magazine in different namespaces. To use both classes in your main script without confusion, you will use aliasing with the as keyword.
🎯 Goal: You will create two classes in separate namespaces, then import them into a single PHP script using aliasing with the as keyword. Finally, you will create objects from these aliased classes and print their types.
📋 What You'll Learn
Create two namespaces: Library\Books and Library\Magazines
Define a class Book inside Library\Books namespace
Define a class Magazine inside Library\Magazines namespace
Use use statements with as keyword to alias these classes in the main script
Create objects from the aliased classes and print their class names
💡 Why This Matters
🌍 Real World
In large PHP projects, many classes may have the same name but live in different namespaces. Aliasing with the <code>as</code> keyword helps developers use these classes clearly without confusion.
💼 Career
Understanding namespaces and aliasing is important for PHP developers working on complex applications, frameworks, or libraries where code organization and avoiding name clashes are critical.
Progress0 / 4 steps
1
Create namespaces and classes
Create two namespaces: Library\Books and Library\Magazines. Inside Library\Books, create a class called Book with an empty body. Inside Library\Magazines, create a class called Magazine with an empty body.
PHP
Need a hint?

Use the namespace keyword to create namespaces. Define classes inside curly braces after the namespace.

2
Import classes with aliasing
In the global namespace, use use statements to import Library\Books\Book as Novel and Library\Magazines\Magazine as Periodical.
PHP
Need a hint?

Use the syntax use Namespace\Class as Alias; to create an alias.

3
Create objects from aliased classes
Create an object called $myNovel from the aliased class Novel and an object called $myPeriodical from the aliased class Periodical.
PHP
Need a hint?

Create objects using the new keyword and the alias names.

4
Print class names of objects
Use echo to print the class name of $myNovel and $myPeriodical using the get_class() function. Print each class name on a new line.
PHP
Need a hint?

Use get_class($object) to get the full class name including namespace. Use echo to print it. Add a newline with "\n".