0
0
PHPprogramming~20 mins

Why namespaces are needed in PHP - See It in Action

Choose your learning style9 modes available
Why namespaces are needed
📖 Scenario: Imagine you are building a website with many parts. Different parts might use the same names for their functions or classes. This can cause confusion for the computer.Namespaces help keep these names separate, like putting things in different boxes so they don't get mixed up.
🎯 Goal: You will create two classes with the same name but in different namespaces. Then you will use both classes in the same program without confusion.
📋 What You'll Learn
Create two namespaces called First and Second
Inside each namespace, create a class called Greeting
Each Greeting class should have a method sayHello() that returns a different message
Use both Greeting classes in the main code by specifying their namespaces
Print the messages from both classes
💡 Why This Matters
🌍 Real World
Namespaces are used in real websites and applications to keep code organized and prevent errors when different parts use the same names.
💼 Career
Understanding namespaces is important for working on large PHP projects and collaborating with other developers without causing conflicts.
Progress0 / 4 steps
1
Create two namespaces with Greeting classes
Create a namespace called First with a class Greeting that has a method sayHello() returning the string 'Hello from First namespace!'. Then create another namespace called Second with a class Greeting that has a method sayHello() returning the string 'Hello from Second namespace!'.
PHP
Need a hint?

Use the namespace keyword to create namespaces. Define classes inside them with the same name.

2
Create objects from both Greeting classes
In the global namespace, create an object called firstGreeting from the class Greeting inside the First namespace. Also create an object called secondGreeting from the class Greeting inside the Second namespace.
PHP
Need a hint?

Use the full class name with namespace like \First\Greeting to create objects.

3
Call sayHello() method on both objects
Call the sayHello() method on the object firstGreeting and store the result in a variable called message1. Then call the sayHello() method on the object secondGreeting and store the result in a variable called message2.
PHP
Need a hint?

Use the arrow -> to call methods on objects and assign the results to variables.

4
Print both messages
Print the variables message1 and message2 each on a new line using echo.
PHP
Need a hint?

Use echo to print text. Add "\n" to move to the next line.