Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy load class in PHP

Tags:

php

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.

like image 714
user4o01 Avatar asked May 17 '12 12:05

user4o01


3 Answers

__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(); 
?>
like image 133
Vlad Balmos Avatar answered Oct 15 '22 18:10

Vlad Balmos


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');
like image 25
Explosion Pills Avatar answered Oct 15 '22 16:10

Explosion Pills


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

like image 38
giorgio Avatar answered Oct 15 '22 17:10

giorgio