Skip to content

PHP Tutorial Namespaces and Autoloading

Namespaced Functions and Constants

Lesson 246 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Namespaces are not only for classes. Functions and constants can live in a namespace too.

Declare them

index.php
PHP
<?php
namespace App\Helpers;

const SITE_NAME = "Code Corner";

function slug(string $text): string
{
    return trim(preg_replace("/[^a-z0-9]+/", "-", strtolower($text)), "-");
}

echo \App\Helpers\slug("Hello, World!") . " / " . \App\Helpers\SITE_NAME;
Output
OUTPUT
hello-world / Code Corner

Note: a namespaced constant is declared with const, not define() (a define() name is global unless you write the namespace in the string yourself).

Use them with use function and use const

index.php
PHP
<?php
namespace App\Helpers {
    function slug(string $text): string
    {
        return trim(preg_replace("/[^a-z0-9]+/", "-", strtolower($text)), "-");
    }

    const SITE_NAME = "Code Corner";
}

namespace Main {
    use function App\Helpers\slug;
    use const App\Helpers\SITE_NAME;

    echo slug("PHP Namespaces") . " on " . SITE_NAME;
}
Output
OUTPUT
php-namespaces on Code Corner

Without those imports, you would write the full name: \App\Helpers\slug(...).

The fallback rule

When you call strlen() inside a namespace, PHP first looks for Current\Namespace\strlen. If it does not exist, PHP falls back to the global strlen. That is why built-in functions work without a backslash.

index.php
PHP
<?php
namespace Demo;

echo strlen("abc") . " and " . PHP_INT_SIZE;
Output
OUTPUT
3 and 8

Both the function strlen() and the constant PHP_INT_SIZE were found in the global namespace.

Speed tip

Writing a leading backslash (\strlen()) or importing the function lets PHP skip the first lookup. In rare, hot code paths this can help. In most code, do not bother.

Autoloading and functions

PSR-4 autoloading works for classes only. Functions and constants in a namespace are not autoloaded. If you have helper functions, Composer can load a file for you with the files setting in composer.json:

data.json
JSON
{
    "autoload": {
        "files": ["src/helpers.php"]
    }
}

The file loads on every request. Keep helper files small.

A good alternative

Rather than loose functions, many projects put helpers in a class as static methods (Str::slug()) so that autoloading works and the names are grouped.

index.php
PHP
<?php
namespace App\Support;

final class Str
{
    public static function slug(string $text): string
    {
        return trim(preg_replace("/[^a-z0-9]+/", "-", strtolower($text)), "-");
    }
}

echo \App\Support\Str::slug("Static Helpers Work");
Output
OUTPUT
static-helpers-work
info
Why this matters in WordPress
WordPress functions are global and use prefixes such as wp_ to avoid clashes. If you write a modern plugin, put your functions in a namespace, and your code cannot collide with another plugin’s helper that has the same name.