문제

I am just learning how to use spl_autoload_register

I have a folder structure that looks like this:

lib/projectname/home/homepage.php

so if I include the file like this it works:

include("lib/projectname/home/homepage.php");
$home = new homepage();

I have added in an autoload.php file which looks like this:

function myclass($class_name) {
   $class_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name) . '.php';
   require_once($class_name);
 }

spl_autoload_register('myclass');

Now if I try to use the class I am referencing it like this:

require_once("autoload.php");

$home = new lib_projectname_home_homepage;

when i do this, i get the following error:

Fatal error: Class 'lib_projectname_home_homepage' not found

So it appears as if the loading of the class file is working, but its not finding the class inside the file?

The actual homepage.php file looks like this:

class homepage {

    function __construct(){

        echo "homepage";
    }

}

What do I need to change in order to make this work properly?

도움이 되었습니까?

해결책

change

class homepage {
    function __construct(){
        echo "homepage";
    }
}

to

class lib_projectname_home_homepage {
    function __construct(){
        echo "homepage";
    }
}

or change:

require_once($class_name);

to

require_once('lib/projectname/home/' . $class_name);

and then:

$home = new homepage();

concept of autoloader is simply to find class with a given name. it does not change class name on the fly.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top