user2287873
user2287873

Reputation: 615

Don't understand why autoload isn't working

So here's my autoload -

function __autoload($classname){
  include $classname.'.php';
}

I also tried using DOCROOT just in case....

function __autoload($classname){
  define('DOCROOT', dirname(__FILE__));
  include DOCROOT.'/'.$classname.'.php';
}

But when it comes across the PatentAssignment class, it says that it can't find the definition for the class...

Yet if I have an

include 'PatentAssignment.php';

in the constructor for the class that will use it, everything works fine. Not sure what is going on. In fact, it's not even calling autoload, just goes and gets confused about what to do.

Upvotes: 0

Views: 212

Answers (3)

luqita
luqita

Reputation: 4085

Try this:

    spl_autoload_register(function($class) {
    //your function here
    return class_exists($class, false);
   });

Upvotes: 0

Daniel W.
Daniel W.

Reputation: 32350

What does the constructor look like (with the include)? Put the autoload code before all class definition, best at top of the initializing php file. Try debugging:

function __autoload($classname) {
  echo 'looking for ' . $classname . ' in ' . getcwd();
  include $classname.'.php';
}
  1. http://php.net/manual/en/function.getcwd.php

Get the current working directory. Are all your files in the same folder?

  1. http://de3.php.net/manual/en/function.spl-autoload.php

Use spl_autoload instead:

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

Upvotes: 1

HorusKol
HorusKol

Reputation: 8706

__autoload() is not supposed to be a member method of a class - it is supposed to be a standalone function in the global namespace.

http://php.net/manual/en/language.oop5.autoload.php

Upvotes: 1

Related Questions