7

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.

3 Answers 3

6

__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(); 
?>
Sign up to request clarification or add additional context in comments.

6 Comments

He shouldn't use __autoload at all
@ExplosionPills Could you explain why you say so? I am curious myself.
@sprain He should write an autoload function called something else, perhaps as part of a class as he has done, and then call spl_autoload_register. Imagine this code is on a huge website with many criss-crossing dependencies on pages. What if someone has already used __autoload on an app that goes untested that happens to include the file where he is defining the other __autoload.
can you please clarify by a sample code i am curious about you solution
@ExplosionPills that's true. but for a beginner trying to understand how all this works __autoload is the most simple method to get him going. IMHO
|
4

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');

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.