This post regarding how to autoload classes in PHP without included require method.
Some rules you have to follow.
1) The file name must be the class name.
Like if you declare a class like SampleClass then your file name should be the same name.
2) If you declare a namespace then your folder name must be the namespace name and under file name must be the class name as the first rule.
Now, let’s take an example.
I have created some file under these files I declared classes like below
Calculator.php
<?php class Calculator{ public function __construct($i){ echo "This is a Calculator constructor = ".$i.""; } public function testCalculator(){ echo "This is a Calculator test method"; } } ?>
InterfaceClass.php
<?php Interface InterfaceTest{ public function testInterface(); } class InterfaceClass implements InterfaceTest{ public function testInterface(){ echo "This is a interface method"; } } ?>
SampleTest.php
<?php class SampleTest{ public function __construct($i){ echo "This is a constructor = ".$i.""; } public function testMethod(){ echo "This is a test method"; } } ?>
init.php (This is the page which is used to load all classes using spl_autoload_register method with a parameter name $class_name )
<?php spl_autoload_register(function($class_name){ // this line is used for load namespace. $class_name = str_replace(" \ ", " / " , $class_name); // if you want to load only classes the you remove above line. require_once "{$class_name}.php"; }); ?>
Product.php under App directory and you can see that I defined the folder name same as the namespace name.
<?php namespace App; class Product{ public function productName($name){ echo "Namespace test method and product name is:".$name; } } ?>
main.php (This is the main page and include the init.php)
<?php require_once('init.php'); $obj = new SampleTest(3); $obj->testMethod(); echo "<br>++++++++++++++++++++++++++++++"<br>"; $objC= new Calculator(5); $objC->testCalculator(); echo "<br>++++++++++++++++++++++++++++++"<br>"; $objI= new InterfaceClass; $objI->testInterface(); echo "<br>++++++++++++++++++++++++++++++"<br>"; $objP= new App\Product; $objP->productName('Mango'); ?>
If you execute the main.php file then you can see the output like below screenshot.