DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

Autoload classes in PHP

Here's a new problem to solve, How would you include classes without having to write include 'path-to-class-file' on top of the file for every class file- that needs to be included?

Using spl_autoloader_register function.

Here's the directory structure

Alt Text

So what do we write in the autoloader.inc.php file?

<?php


spl_autoload_register('autoLoader');

function autoLoader($className){
    $path  = "classes/";
    $extension = ".class.php";
    $fullPath  = $path.$className.$extension;

    if(!file_exists($fullPath)){
        return false;

    }

    include_once $fullPath;
}


?>

Now we can easily include the autoloader file in the index.php file which then will give access to any class file we have in the classes directory.

Here's whats in the index.php file

<?php
  <?php 
include 'includes/autoloader.inc.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <?php

      $tesla = new Car("Modelx","black","2019");

      echo $tesla->getName();
      echo  "<br>";
      echo $tesla->getbodyColor();
      echo  "<br>";
      echo $tesla->getYear();

       $tesla->setName("ModelY");  
       echo  "<br>"; 
       echo  "<br>"; 
       echo $tesla->getName();  
       echo "<br>" ;
        echo Car::$NoOfTyres;
        Car::setNoOfTyres(6);
        echo "<br>";
        echo Car::$NoOfTyres;

    ?>
</body>
</html>
?>

You will get the out put as follows:

Alt Text

Top comments (3)

Collapse
 
felixdorn profile image
Félix Dorn

You could also take a look at Composer and modern development practices. :)

Collapse
 
msamgan profile image
Mohammed Samgan Khan

i just scrolled down to comments just to say that, composer is way more easy to use..

Collapse
 
naveenkolambage profile image
Naveen Dinushka

Thanks guys :) I m learning from you!