0
0
PHPprogramming~5 mins

Manual includes vs autoloading in PHP

Choose your learning style9 modes available
Introduction

We use manual includes or autoloading to bring code from other files into our program. This helps organize code and reuse it without copying.

When you want to use a class or function defined in another file.
When your project grows and you have many files to manage.
When you want to avoid writing many include or require statements manually.
When you want PHP to load classes automatically when needed.
When you want cleaner and easier to maintain code.
Syntax
PHP
<?php
// Manual include
include 'filename.php';

// Autoloading example
spl_autoload_register(function ($class) {
    include $class . '.php';
});

Manual include loads a file explicitly where you write the statement.

Autoloading loads classes automatically when you create an object of that class.

Examples
This manually includes the file 'MyClass.php' before using the class.
PHP
<?php
include 'MyClass.php';
$obj = new MyClass();
This sets up autoloading so PHP loads 'MyClass.php' automatically when creating MyClass object.
PHP
<?php
spl_autoload_register(function ($class) {
    include $class . '.php';
});
$obj = new MyClass();
Sample Program

This example shows two ways to use the MyClass class: first by manually including the file, then by using autoloading.

PHP
<?php

// File: manual_include.php
include 'MyClass.php';
$obj1 = new MyClass();
$obj1->sayHello();

// File: autoload_example.php
spl_autoload_register(function ($class) {
    include $class . '.php';
});
$obj2 = new MyClass();
$obj2->sayHello();
OutputSuccess
Important Notes

Manual includes require you to write include or require for every file you need.

Autoloading helps avoid errors from missing includes and keeps code cleaner.

Autoloading works well with classes but not with functions or variables.

Summary

Manual includes load files explicitly where you write the code.

Autoloading loads classes automatically when you create objects.

Autoloading makes managing many files easier and reduces errors.