0
0
PHPprogramming~20 mins

Sub-namespaces in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Sub-namespace Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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();
AFatal error: Class 'App\Controllers\Profile' not found
BNULL
CApp\Models\User\Profile
DUser Profile
Attempts:
2 left
💡 Hint
Look at how the class is imported with 'use' and instantiated.
🧠 Conceptual
intermediate
1:30remaining
Understanding sub-namespace declaration
Which of the following is the correct way to declare a sub-namespace in PHP?
Anamespace App\Models\User;
Bnamespace App.Models.User;
Cnamespace App/Models/User;
Dnamespace App:Models:User;
Attempts:
2 left
💡 Hint
PHP namespaces use backslashes to separate levels.
🔧 Debug
advanced
2: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();
AFatal error: Uncaught Error: Class 'Profile' not found
BFatal error: Uncaught Error: Class 'App\Models\User\Profile' not found
CNo error, code runs fine
DParse error: syntax error, unexpected token '$profile'
Attempts:
2 left
💡 Hint
Consider the current namespace when instantiating classes without 'use'.
📝 Syntax
advanced
1: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.
A
&lt;?php
use App:Models:User:Profile;
$profile = new Profile();
B
&lt;?php
use App.Models.User.Profile;
$profile = new Profile();
C
&lt;?php
use App\Models\User\Profile;
$profile = new Profile();
D
&lt;?php
use App/Models/User/Profile;
$profile = new Profile();
Attempts:
2 left
💡 Hint
Remember the correct namespace separator in 'use' statements.
🚀 Application
expert
2: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:
A4
B3
C2
D1
Attempts:
2 left
💡 Hint
Count all classes declared in 'App\Models' and any namespace starting with it.