0
0
PHPprogramming~15 mins

Global namespace access in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Global Namespace Access in PHP
📖 Scenario: Imagine you are writing a PHP script that uses a function named strlen to find the length of a string. However, you also have a custom function named strlen inside a namespace. You want to use the original PHP strlen function from the global namespace.
🎯 Goal: You will create a namespaced function with the same name as a global PHP function, then learn how to call the global function explicitly using the global namespace access.
📋 What You'll Learn
Create a namespace called MyApp
Inside MyApp, create a function called strlen that returns a fixed number
Create a variable $text with the value 'Hello'
Call the global strlen function on $text using global namespace access
Print the result of the global strlen function call
💡 Why This Matters
🌍 Real World
Namespaces help organize code and avoid name conflicts in large PHP projects.
💼 Career
Understanding namespaces and global namespace access is important for working with modern PHP frameworks and libraries.
Progress0 / 4 steps
1
Create a namespace and a custom strlen function
Create a namespace called MyApp. Inside it, define a function called strlen that takes one parameter $str and returns the number 42.
PHP
Need a hint?

Use the namespace keyword to create a namespace. Define the function inside curly braces.

2
Create a variable with a string value
Outside the MyApp namespace, create a variable called $text and set it to the string 'Hello'.
PHP
Need a hint?

Just create a variable $text and assign the string 'Hello' to it.

3
Call the global strlen function using global namespace access
Create a variable called $length and set it to the result of calling the global strlen function on $text using the global namespace access operator \.
PHP
Need a hint?

Use \strlen($text) to call the global PHP function strlen explicitly.

4
Print the length from the global strlen function
Print the value of the variable $length using echo.
PHP
Need a hint?

Use echo $length; to display the length.