Home » Php » Lazy load class in PHP

Lazy load class in PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to lazy load class but with no success

<?php

class Employee{

    function __autoload($class){

        require_once($class);
    }


    function display(){

        $obj = new employeeModel();
        $obj->printSomthing();
    }
}

Now when I make this

function display(){
            require_once('emplpyeeModel.php');
            $obj = new employeeModel();
            $obj->printSomthing();
        }

It works but I want to lazy load the class.

How to&Answers:

Change Employee a bit:

class Employee {

   public static function __autoload($class) {
      //_once is not needed because this is only called once per class anyway,
      //unless it fails.
      require $class;
   }

   /* Other methods Omitted */
}
spl_autoload_register('Employee::__autoload');

Answer:

__autoload is a standalone function not a method of a class. Your code should look like this:

<?php

class Employee{

    function display(){

        $obj = new employeeModel();
        $obj->printSomthing();
    }
}

function __autoload($class) {
    require_once($class.'.php');
}

function display(){
    $obj = new Employee();
    $obj->printSomthing();
}

UPDATE

Example taken from the php manual:

<?php
function __autoload($class_name) {
    include $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>

Answer:

First if all it’s better to use spl_autoload_register() (check the note in php’s manual for autoloading).

Then back to your problem; only if the display() function is in the same directory as the employeeModel this will work. Otherwise, use absolute paths (see also include() and include_path setting