0
0
PHPprogramming~30 mins

Importing with use keyword in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Importing with use keyword
📖 Scenario: Imagine you are organizing a small library of books. Each book belongs to a category, and you want to use short names to refer to these categories in your code.
🎯 Goal: You will create two classes in different namespaces and then use the use keyword to import these classes with shorter names. Finally, you will create objects from these classes and print their category names.
📋 What You'll Learn
Create two classes in separate namespaces: Library\Fiction\Book and Library\NonFiction\Book
Each class should have a public method getCategory() that returns the string 'Fiction' or 'Non-Fiction' respectively
Use the use keyword to import these classes with aliases FictionBook and NonFictionBook
Create objects of FictionBook and NonFictionBook and print their categories
💡 Why This Matters
🌍 Real World
Namespaces and the <code>use</code> keyword help organize large PHP projects by grouping related code and avoiding name conflicts.
💼 Career
Understanding namespaces and imports is essential for working on professional PHP applications, frameworks, and libraries.
Progress0 / 4 steps
1
Create two classes in namespaces
Create two classes: Book inside namespace Library\Fiction and another Book inside namespace Library\NonFiction. Each class should have a public method getCategory() that returns 'Fiction' for the first and 'Non-Fiction' for the second.
PHP
Need a hint?

Use the namespace keyword to define namespaces. Define the Book class inside each namespace with the getCategory() method returning the correct string.

2
Import classes with use keyword and alias
After the namespace declarations, use the use keyword to import Library\Fiction\Book as FictionBook and Library\NonFiction\Book as NonFictionBook.
PHP
Need a hint?

Use the use keyword followed by the full namespace and class name, then as and the alias name.

3
Create objects using the aliases
Create two variables: $fictionBook as a new FictionBook object and $nonFictionBook as a new NonFictionBook object.
PHP
Need a hint?

Create new objects by calling new with the alias names.

4
Print the categories of the books
Print the category of $fictionBook by calling getCategory() and then print the category of $nonFictionBook by calling getCategory(). Each category should be printed on its own line.
PHP
Need a hint?

Use print() to display the category strings returned by getCategory(). Add a newline character \n after each.