0
0
PHPprogramming~15 mins

Namespace declaration syntax in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Namespace declaration syntax
📖 Scenario: Imagine you are organizing your PHP code into different sections to keep it neat and avoid name clashes. Namespaces help you do this by grouping related code together.
🎯 Goal: You will create a PHP file that declares a namespace and defines a simple function inside it. Then you will access that function using the namespace.
📋 What You'll Learn
Declare a namespace called MyApp\Utils
Create a function called greet inside the namespace that returns the string 'Hello from Utils!'
Call the greet function using the full namespace path
Print the result of the function call
💡 Why This Matters
🌍 Real World
Namespaces help large PHP projects stay organized by grouping related code and avoiding name conflicts.
💼 Career
Understanding namespaces is important for working on professional PHP applications and frameworks that use modular code.
Progress0 / 4 steps
1
Declare the namespace
Write a PHP file that declares a namespace called MyApp\Utils at the top.
PHP
Need a hint?

Use the namespace keyword followed by MyApp\Utils; at the top of the file.

2
Create a function inside the namespace
Add a function called greet inside the MyApp\Utils namespace that returns the string 'Hello from Utils!'.
PHP
Need a hint?

Define a function named greet that returns the exact string 'Hello from Utils!'.

3
Call the namespaced function
Outside the namespace, call the greet function using the full namespace path MyApp\Utils\greet() and store the result in a variable called message.
PHP
Need a hint?

Use the full namespace path with a leading backslash to call the function: \MyApp\Utils\greet().

4
Print the result
Print the value of the variable $message to display the greeting.
PHP
Need a hint?

Use print($message); to show the greeting on the screen.