spl_autoload_register not displaying

I am having problem in using the spl_autoload_register, .I always get error
“Warning: require(myapp\classes\Employee.php): failed to open stream”

    //classes/Employee.php

<?php
namespace myapp\classes;

class Employee{

    public function Firstname()
    {

        echo "Firstname method";
    }

    public function Lastname()
    {


        echo "Last Name method";
    }

    public function employeedisplay(){
        return $this->Firstname() + $this->Lastname();
    }



}

// index.php

use myapp\classes\Employee;


require_once 'init.php';


$emp = new Employee();

$emp->employeedisplay();


//init.php


spl_autoload_register(function ($class) {
   
    require  $class. '.php';
});

Is it correct path to your file?
If not, you have to convert class name ($class) into correct path in your autoload function

Here is sample code:

spl_autoload_register(function ($class) {
    $pathParts = explode('\', trim($class, '\'));
    unset($pathParts[0]);   
    $path = implode(DIRECTORY_SEPARATOR, $pathParts);
    require  $path . '.php';
});

This function does the following:

  1. Explodes class name into parts ('myapp\classes\Employee' => ['myapp', 'classes', 'Employee'])
  2. Removes first part (['myapp', 'classes', 'Employee'] => ['classes', 'Employee'])
  3. Glues remaining parts using OS directory separator (['classes', 'Employee'] => 'classes/Employee')
  4. Adds .php and includes the file

So, if your class has a name myapp\classes\Employee it will search for it in classes/Employee.php

Thanks.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.