Bird
Raised Fist0
PHPprogramming~10 mins

Sub-namespaces in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Sub-namespaces
Declare main namespace
↓
Declare sub-namespace
↓
Define class/function in sub-namespace
↓
Use fully qualified name or import
↓
Access class/function in sub-namespace
This flow shows how PHP code declares a main namespace, then a sub-namespace inside it, defines code there, and accesses it using full or imported names.
Execution Sample
PHP
<?php
namespace Main\Sub;
class Test {
  public function say() { return "Hello from Sub!"; }
}
$obj = new \Main\Sub\Test();
echo $obj->say();
Defines a class inside a sub-namespace and creates an object using the full namespace path, then calls a method.
Execution Table
StepCode LineActionNamespace ContextResult/Output
1namespace Main\Sub;Declare sub-namespace inside MainMain\SubNamespace set to Main\Sub
2class Test {...}Define class Test inside Main\SubMain\SubClass Test available in Main\Sub
3$obj = new \Main\Sub\Test();Create object using full namespaceGlobalObject of Main\Sub\Test created
4echo $obj->say();Call say() method on objectGlobalOutputs: Hello from Sub!
💡 Code finishes after outputting the string from the sub-namespace class method.
Variable Tracker
VariableStartAfter Step 3After Step 4
$objundefinedInstance of Main\Sub\TestInstance of Main\Sub\Test
Key Moments - 2 Insights
Why do we use a backslash before Main\Sub when creating the object?
The backslash means we use the full global namespace path. Without it, PHP looks inside the current namespace, which might cause errors. See step 3 in execution_table.
Can we define multiple sub-namespaces inside one file?
Yes, but each namespace block must be declared separately. Here, we only use one sub-namespace 'Main\Sub' as shown in step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the namespace context when the class Test is defined?
AMain\Sub
BMain
CGlobal
DUndefined
💡 Hint
Check step 2 in the execution_table where the class is defined.
At which step is the object $obj created?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for the line with 'new \Main\Sub\Test()' in the execution_table.
If we remove the leading backslash in 'new \Main\Sub\Test()', what happens?
AObject is created successfully
BPHP looks in current namespace and may cause error
CNamespace changes to global automatically
DNo effect, same output
💡 Hint
Refer to key_moments question about the backslash usage.
Concept Snapshot
PHP sub-namespaces are declared with namespace Main\Sub; inside a file.
Classes/functions inside belong to that sub-namespace.
Use leading backslash for full path: new \Main\Sub\ClassName();
Without backslash, PHP looks inside current namespace.
Sub-namespaces help organize code hierarchically.
Full Transcript
This example shows how PHP uses sub-namespaces to organize code. First, the code declares namespace Main\Sub, which means everything inside belongs to that sub-namespace. Then, a class Test is defined inside it. When creating an object, the code uses the full path with a leading backslash: new \Main\Sub\Test(). This tells PHP to look from the global namespace root. Calling the say() method on the object outputs a string. The execution table traces each step, showing namespace context and results. The variable tracker shows how $obj changes from undefined to an instance. Key moments explain why the backslash is important and how namespaces work. The quiz tests understanding of namespace context, object creation step, and effects of removing the backslash. The snapshot summarizes the main points about sub-namespaces in PHP.

Practice

(1/5)
1. What is the main purpose of using sub-namespaces in PHP?
easy
A. To make code run faster
B. To organize code into smaller groups inside bigger groups
C. To change variable types automatically
D. To create new data types

Solution

  1. Step 1: Understand what sub-namespaces do

    Sub-namespaces help organize code by grouping related classes or functions inside bigger groups.
  2. Step 2: Compare options with this purpose

    Only To organize code into smaller groups inside bigger groups describes organizing code into smaller groups inside bigger groups, which matches the purpose of sub-namespaces.
  3. Final Answer:

    To organize code into smaller groups inside bigger groups -> Option B
  4. Quick Check:

    Sub-namespaces organize code = To organize code into smaller groups inside bigger groups [OK]
Hint: Sub-namespaces group code inside bigger groups [OK]
Common Mistakes:
  • Thinking sub-namespaces speed up code
  • Confusing sub-namespaces with data types
  • Believing sub-namespaces change variable types
2. Which of the following is the correct way to declare a sub-namespace inside App\Controllers?
easy
A. namespace App.Controllers.Admin;
B. namespace App/Controllers/Admin;
C. namespace App\Controllers\Admin;
D. namespace App-Controllers-Admin;

Solution

  1. Step 1: Recall PHP namespace separator

    PHP uses backslashes (\\) to separate namespace levels, not slashes or dots.
  2. Step 2: Check each option for correct syntax

    namespace App\Controllers\Admin; uses backslashes correctly. Options A, B, and D use slashes, dots, or dashes, which are invalid.
  3. Final Answer:

    namespace App\\Controllers\\Admin; -> Option C
  4. Quick Check:

    Backslash separates namespaces = namespace App\Controllers\Admin; [OK]
Hint: Use backslashes (\\) to separate namespace levels [OK]
Common Mistakes:
  • Using forward slashes instead of backslashes
  • Using dots or dashes in namespace names
  • Missing the semicolon at the end
3. What will be the output of this PHP code?
namespace App\Models\User;

class Profile {
    public function getName() {
        return "Alice";
    }
}

$profile = new \App\Models\User\Profile();
echo $profile->getName();
medium
A. Alice
B. Error: Class not found
C. Empty output
D. Fatal error: Syntax error

Solution

  1. Step 1: Understand the namespace and class usage

    The class Profile is declared inside the namespace App\\Models\\User. The object is created using the fully qualified name with leading backslash.
  2. Step 2: Check the method call and output

    The getName() method returns "Alice", so echoing it prints "Alice".
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    Fully qualified class call returns "Alice" [OK]
Hint: Use leading backslash for full namespace access [OK]
Common Mistakes:
  • Forgetting leading backslash causes class not found
  • Assuming no output without echo
  • Confusing namespace separator with other characters
4. Identify the error in this PHP code using sub-namespaces:
namespace App\Services\Payment

class Processor {
    public function pay() {
        return "Paid";
    }
}
medium
A. Missing semicolon after namespace declaration
B. Class name should be lowercase
C. Method pay() must be static
D. Namespace separator should be a dot

Solution

  1. Step 1: Check namespace declaration syntax

    In PHP, namespace declarations must end with a semicolon (;). This code misses it.
  2. Step 2: Verify other parts

    Class names can be uppercase, methods do not need to be static, and namespace separators are backslashes, not dots.
  3. Final Answer:

    Missing semicolon after namespace declaration -> Option A
  4. Quick Check:

    Namespace line must end with ; [OK]
Hint: Always end namespace line with semicolon [OK]
Common Mistakes:
  • Omitting semicolon after namespace
  • Thinking class names must be lowercase
  • Confusing namespace separator with dots
5. Given these two classes in sub-namespaces:
namespace App\Utils\String;
class Formatter {
    public static function format() {
        return "Formatted String";
    }
}

namespace App\Utils\Number;
class Formatter {
    public static function format() {
        return 12345;
    }
}

// In global namespace
use App\Utils\String\Formatter as StringFormatter;
use App\Utils\Number\Formatter as NumberFormatter;

echo StringFormatter::format() . " and " . NumberFormatter::format();

What is the output?
hard
A. 12345 and 12345
B. Error: Cannot use same class name twice
C. Formatted String and Formatted String
D. Formatted String and 12345

Solution

  1. Step 1: Understand sub-namespaces and aliasing

    Two classes named Formatter exist in different sub-namespaces. Aliases StringFormatter and NumberFormatter are used to avoid name conflicts.
  2. Step 2: Check method calls and outputs

    StringFormatter::format() returns "Formatted String" and NumberFormatter::format() returns 12345. Concatenating them with " and " produces the combined string.
  3. Final Answer:

    Formatted String and 12345 -> Option D
  4. Quick Check:

    Aliases allow same class names in sub-namespaces [OK]
Hint: Use aliases to handle same class names in sub-namespaces [OK]
Common Mistakes:
  • Assuming class name conflict causes error
  • Forgetting to use aliases for same class names
  • Expecting both outputs to be the same
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard