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\BookEach class should have a public method
getCategory() that returns the string 'Fiction' or 'Non-Fiction' respectivelyUse the
use keyword to import these classes with aliases FictionBook and NonFictionBookCreate 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