1

I have a file called Query.php.

namespace Test
{
    class Query
    {
        public function __construct()
        {
            printf("Hello, World");
        }
    }
}

in bootstrap.php I try to call it:

spl_autoload_register(function($className) {
    if(file_exists('../folder/'.$className.'.php'))
    {
        require_once '../folder/'.$className.'.php';
    }
});

new \Test\Query();

Result: Fatal error: class Test\Query not found.

Without namespace it works fine. How to fix it?

Thanks in advance.

tereško
  • 58,060
  • 25
  • 98
  • 150
str.gsub
  • 65
  • 1
  • 1
  • 5

1 Answers1

0

You have to replace the \ with DIRECTORY_SEPARATOR.

define('BASE_PATH', realpath(dirname(__FILE__)));
spl_autoload_register(function($className) {
    if(file_exists(BASE_PATH . '../folder/'. str_replace('\\', DIRECTORY_SEPARATOR , $class). '.php'))
    {
        require_once '../folder/'.$className.'.php';
    }
});

This is assuming your directory structure is the following

/folder/boostrap.php

/folder/Test/Query.php

See How do I use PHP namespaces with autoload?

Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217