Challenge - 5 Problems
Sub-namespace Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing a class in a sub-namespace
What is the output of this PHP code?
PHP
<?php namespace App\Models\User; class Profile { public function getName() { return "User Profile"; } } namespace App\Controllers; use App\Models\User\Profile; $profile = new Profile(); echo $profile->getName();
Attempts:
2 left
💡 Hint
Look at how the class is imported with 'use' and instantiated.
✗ Incorrect
The 'use' statement imports the class from the sub-namespace. So creating a new Profile() calls the correct class and outputs 'User Profile'.
🧠 Conceptual
intermediate1:30remaining
Understanding sub-namespace declaration
Which of the following is the correct way to declare a sub-namespace in PHP?
Attempts:
2 left
💡 Hint
PHP namespaces use backslashes to separate levels.
✗ Incorrect
PHP uses backslashes '\\' to separate namespace levels. So 'namespace App\\Models\\User;' is correct.
🔧 Debug
advanced2:00remaining
Identify the error in sub-namespace usage
What error will this PHP code produce?
PHP
<?php namespace App\Models; class User {} namespace App\Models\User; class Profile {} $profile = new Profile();
Attempts:
2 left
💡 Hint
Consider the current namespace when instantiating classes without 'use'.
✗ Incorrect
The code tries to instantiate 'Profile' in the 'App\Models\User' namespace, so it looks for 'Profile' there. However, the instantiation is outside any namespace, so PHP looks for 'Profile' in the global namespace and fails. Without 'use' or fully qualified name, PHP looks for 'Profile' in the global namespace and fails.
📝 Syntax
advanced1:30remaining
Which code snippet correctly imports and uses a sub-namespace class?
Select the option that correctly imports and creates an object from a class in a sub-namespace.
Attempts:
2 left
💡 Hint
Remember the correct namespace separator in 'use' statements.
✗ Incorrect
The 'use' statement must use backslashes '\\' to separate namespaces. Only option C uses the correct syntax.
🚀 Application
expert2:30remaining
Count classes in nested sub-namespaces
Given these PHP files with namespaces and classes, how many classes are declared in the 'App\Models' namespace and all its sub-namespaces combined?
File 1:
Attempts:
2 left
💡 Hint
Count all classes declared in 'App\Models' and any namespace starting with it.
✗ Incorrect
Classes in 'App\Models', 'App\Models\User', and 'App\Models\User\Settings' count. That is User, Profile, and Preferences = 3 classes. The class in 'App\Controllers' does not count.