PHP autoloading classes example with namespaces

A post on why and how to do file autoloading and namespaces in PHP 7.4 plus.

Autoloading files cleans up the code, you no longer have to spam a potential list of includes/requires at the beginning of all your files, this makes maintaining the code better when it is isn’t a structured mess.

The bad method:


Whilst using the autoload feature seems more work than to just doing an include to one file which branches of to many, the idea is when working in a large project autoloading is simple and hassle-free.

php autoload classes

The use of namespaces helps the organisation and importantly avoid function name collisions, they are very critical if your project is open-sourced + composer compatible.


This blog post autoloading example is structured as:


The root has an index.php file and the classes/ directory which contains the backend/ and frontend/ directory along with autoload.php file.

Inside classes/backend/ is users.php and inside classes/frontend/ is html.php and style.php.

The files


require(__DIR__ . '/classes/autoload.php');

use backend\users;
use frontend\html;
use frontend\style;

$html = new html();

$user = new users(1, 'Gary', 'Bilbo');
$user_name = $user->userName();//Gary Bilbo

$html->pageTitle($user_name);//<title>Gary Bilbo</title>
$style = new style();//<style>body{background-color:#b5cde5;};</style>


echo $user->userId();//1


spl_autoload_register(function ($className) {
    $filename = __DIR__ . DIRECTORY_SEPARATOR . str_replace('\\', '/', $className) . '.php';
    if (file_exists($filename)) require_once($filename);

spl_autoload_register() is the inbuilt PHP function that is used to create a queue to process through and autoload files.

autoload.php is the file that gets included (required) in each of your working files.



namespace backend;//Declaring. Code below belongs to backend namespace

class users
    private int $user_id;
    private string $first_name;
    private string $last_name;

    public function __construct(int $id, string $first_name, string $last_name)
        $this->user_id = $id;
        $this->first_name = $first_name;
        $this->last_name = $last_name;

    public function userName(): string
        return "$this->first_name $this->last_name";

    public function userId(): string
        return "$this->user_id";



namespace frontend;

class html
    public function pageTitle(string $title): void
        echo "<title>$title</title>";

    public function tagOpen(string $tag): void
        echo "<$tag>";

    public function tagClose(string $tag): void
        echo "</$tag>";



namespace frontend;

class style
    public function __construct()
        echo "<style>body{background-color:#b5cde5;};</style>";

Source code from index.php output:

<head><title>Gary Bilbo</title><style>body{background-color:#b5cde5;};</style></head>1