Challenge - 5 Problems
Namespace Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate1:30remaining
Why use namespaces in PHP?
Which of the following best explains why namespaces are needed in PHP?
Attempts:
2 left
💡 Hint
Think about what happens if two parts of a program use the same class name.
✗ Incorrect
Namespaces help prevent conflicts by allowing the same class or function names to exist in different parts of a program without clashing.
❓ Predict Output
intermediate2:00remaining
Output with and without namespaces
What will be the output of this PHP code?
PHP
<?php namespace A; class Test { public function say() { return 'Hello from A'; } } namespace B; class Test { public function say() { return 'Hello from B'; } } namespace { $a = new \A\Test(); $b = new \B\Test(); echo $a->say() . ' and ' . $b->say(); }
Attempts:
2 left
💡 Hint
Look at how the classes are called with their full namespace paths.
✗ Incorrect
Each namespace defines its own Test class, so both can exist and be used separately.
🔧 Debug
advanced1:30remaining
Identify the error caused by missing namespace
What error will this PHP code produce?
PHP
<?php namespace A; class Test {} namespace B; class Test {} namespace { $obj = new Test(); }
Attempts:
2 left
💡 Hint
Consider which namespace the code is running in when creating the object.
✗ Incorrect
The code tries to create an object of class Test without specifying a namespace, but no global Test class exists.
📝 Syntax
advanced1:30remaining
Correct namespace usage syntax
Which option shows the correct way to declare and use a namespace in PHP?
Attempts:
2 left
💡 Hint
Unqualified class names inside a namespace resolve to classes in that namespace.
✗ Incorrect
Inside a namespace, an unqualified class name like 'User' resolves to MyApp\User. Option B is correct; A refers to MyApp\MyApp\User, B has a syntax error (missing semicolon), and C refers to the global User.
🚀 Application
expert2:30remaining
How namespaces solve real-world conflicts
Imagine two large PHP libraries both define a class named Logger. Without namespaces, what problem occurs and how do namespaces solve it?
Attempts:
2 left
💡 Hint
Think about what happens when two classes have the same name in the same program.
✗ Incorrect
Namespaces prevent class name collisions by allowing identical class names to exist in separate namespaces, avoiding overwriting or errors.