0
0
PHPprogramming~10 mins

Why namespaces are needed in PHP - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a namespace named MyApp.

PHP
<?php
namespace [1];

class User {}
Drag options to blanks, or click blank then click option'
AApp
BNamespace
CMyApp
DUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using reserved words as namespace names
Omitting the namespace keyword
2fill in blank
medium

Complete the code to use the class User from the namespace MyApp.

PHP
<?php
use [1]\User;

$user = new User();
Drag options to blanks, or click blank then click option'
AApp
BMyApp
CNamespace
DUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong namespace name
Forgetting to import the class
3fill in blank
hard

Fix the error in the code by completing the blank to refer to the global class Exception.

PHP
<?php
try {
    throw new \[1]("Error occurred");
} catch (\Exception $e) {
    echo $e->getMessage();
}
Drag options to blanks, or click blank then click option'
AException
BError
CThrowable
DErrorException
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the leading backslash
Using wrong class names
4fill in blank
hard

Fill both blanks to create a namespace and define a class inside it.

PHP
<?php
namespace [1];

class [2] {}
Drag options to blanks, or click blank then click option'
AShop
BUser
CApp
DProduct
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing namespace and class names
Using invalid identifiers
5fill in blank
hard

Fill all three blanks to import a class and create its instance.

PHP
<?php
use [1]\[2];

$obj = new [3]();
Drag options to blanks, or click blank then click option'
AMyApp
BUser
DApp
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong namespace or class names
Forgetting to import before instantiation