I’m trying to create a function that will autoload classes, so I can do something like this:
load_class('Db');
$db->query();
Here’s my code so far. It loads the file and instantiates the class successfully, but when I try to call a method like above, I get Call to member function error.
Here’s my code:
function load_class($class) {
$file = 'classes/' . $class . '.php';
if (file_exists($file)) {
include_once($file);
if (class_exists($class)) {
$class = new $class();
return $class;
}
}
}
What am I missing?
Thanks!
load_classreturn the instance ofDbclass, if it found the declaration.You may need to do:
But, If you want to autoload the class when you do
$db = new Db;, then you should take a look at the php’s autoload.Example: