0
0
PHPprogramming~20 mins

Sub-namespaces in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Sub-namespaces in PHP
📖 Scenario: You are organizing a PHP project for a small library system. To keep the code clean and easy to manage, you want to use sub-namespaces to separate different parts of the system.
🎯 Goal: Create a PHP script that defines a main namespace and a sub-namespace. Then, create a class inside the sub-namespace and use it in the main script.
📋 What You'll Learn
Create a main namespace called Library
Create a sub-namespace inside Library called Books
Define a class called Book inside the Library\Books namespace
Create an instance of the Book class and print a message using a method from that class
💡 Why This Matters
🌍 Real World
Organizing code in large PHP projects by grouping related classes into sub-namespaces helps keep the code clean and easy to maintain.
💼 Career
Understanding namespaces and sub-namespaces is important for working on professional PHP projects, frameworks, and libraries.
Progress0 / 4 steps
1
Create the main namespace and sub-namespace with a class
Write PHP code to create a namespace called Library\Books. Inside it, define a class called Book with a public method getTitle() that returns the string 'PHP Basics'.
PHP
Need a hint?

Use the namespace keyword followed by Library\Books. Then define the class Book with the method getTitle() returning the exact string.

2
Create a variable to hold the full class name
Add a variable called bookClass and set it to the string 'Library\\Books\\Book' (note the double backslashes).
PHP
Need a hint?

Remember to escape backslashes in PHP strings by using double backslashes.

3
Create an instance of the Book class using the variable
Use the variable $bookClass to create a new instance called $book of the Book class.
PHP
Need a hint?

Use the variable class name syntax: new $bookClass().

4
Print the book title using the getTitle() method
Write a print statement to display the result of calling getTitle() on the $book object.
PHP
Need a hint?

Use print($book->getTitle()); to show the book title.