This page looks best with JavaScript enabled

Autoloading in PHP

 ·  ☕ 1 min read  ·  🤖 Arjit Sharma

Autoloader is a strategy for finding PHP class or interface and loading it at run time when a class is instantiated. Better than writing multiple require and include as they do not scale well and is a clutter.

Make 2 files ⇒

  • Greet.php(This is the class file we want to load)
  • mainFile.php(It will consume/use Greet.php)
    Note: Keep file name and class name same.
1
2
3
4
5
6
7
<?php
class Greet{
  public function sayHello(){
      echo "Hello World From autoload";
  }
}
?>
1
2
3
4
5
6
7
8
9
<?php
spl_autoload_register(function($class){
  require_once "{$class}.php";
});

$ob = new Greet();
$ob->sayHello();//Output : Hello World From autoload
?>

Share on

Arjit Sharma
WRITTEN BY
Arjit Sharma
Yo, I am a CS enthusiast or am I ? Just kidding.


What's on this Page