Lazy load class in PHP

I want a lazy loading class, but without success

<?php class Employee{ function __autoload($class){ require_once($class); } function display(){ $obj = new employeeModel(); $obj->printSomthing(); } } 

Now when i do it

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

This works, but I want to be lazy to load the class.

+7
source share
3 answers

Change the Employee 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'); 
+4
source

__ autoload is a standalone function, not a class method. 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 php manual:

 <?php function __autoload($class_name) { include $class_name . '.php'; } $obj = new MyClass1(); $obj2 = new MyClass2(); ?> 
+6
source

First, if it’s best to use spl_autoload_register () (check the note in the php manual for startup).

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

+1
source

All Articles