命名空间 - __autoload()需要一个错误的类

I am builded a new object in my file without namespaces:

new My\Validator();

Above, in the same file I have got __autoload():

function __autoload($className) 
{
    var_dump($className);
}

The __autoload() function prints

'My\My\Validator'.  

Where is the double 'My' come from?

It is adding the My namespace because you are probably inside the My namespace already when you create the object with new My\Validator().

namespace My;
$obj = new My\Validator();

will be translated to:

$obj = new My\My\Validator();

Since you are inside the My namespace already you can:

  • either just call new Validator()
  • or call new \My\Validator()

The beginning \ will tell PHP to look into the global namespace.


On a side note, it is considere good practice to use spl_autoload_register instead of __autoload, because you can set multiple autoloader callbacks.