Namespaces are not only for classes. Functions and constants can live in a namespace too.
Declare them
<?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;
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
<?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;
}
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.
<?php
namespace Demo;
echo strlen("abc") . " and " . PHP_INT_SIZE;
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:
{
"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.
<?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");
static-helpers-work
Why this matters in WordPress
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.