CodeBlanks Logo Icon CodeBlanks

Global namespace

PHP course · Advanced · Lesson 30/92

Learn the global namespace with leading \ and global function calls.

Global namespace

Code with no namespace declaration lives in the global namespace. From inside another namespace, reach a global class by prefixing \: \DateTime, \strlen.

PHP first looks in the current namespace, then falls back to the global namespace; this is called fallback. The \ prefix is recommended for classes; fallback is more common for functions and constants.

The \ prefix is recommended for classes

Inside a namespace, writing new DateTime() makes PHP first look for App\DateTime; if missing, it falls back to global DateTime. But this triggers a fallback search every time and may cause unexpected behavior.

So writing global classes as \DateTime is recommended. For functions, fallback is safer; a local function is rarely defined.

Exercise Call global classes from inside a namespace

Define namespace App;. Create a date with new \DateTime("2026-01-15") and print its format("Y-m-d") output. Then print the result of \count([10, 20, 30]).

Show example solution
Write $date = new \DateTime("2026-01-15");. Print the date with echo $date->format("Y-m-d") . "\n";. Print the count with echo \count([10, 20, 30]) . "\n";.
Example solution:
<?php

namespace App;

$date = new \DateTime("2026-01-15");
echo $date->format("Y-m-d") . "\n";
echo \count([10, 20, 30]) . "\n";

Test yourself

  1. Match the global namespace concepts

    \DateTime
    Global class
    no namespace
    You are global
    \strlen()
    Global function
    fallback
    If missing, tries global
  2. How do you call global strlen from inside a namespace?

    • namespace\strlen()
    • global strlen()
    • ::strlen()
    • \strlen()
    Show answer

    \strlen() — Correct. The \ prefix calls the global strlen function.

  3. Complete the global class access

    <?php
    namespace App;
    
    $date = new ____();
    echo $date->format("Y");
    
    Show answer
    <?php
    namespace App;
    
    $date = new \DateTime();
    echo $date->format("Y");
    

All lessons in Advanced