简体   繁体   中英

autoload and namespace

Suppose I have classes in same namespaces:

directory :

  • (folder) a

    • a.php
  • (folder) b

    • b.php
    • c.php

and we use namespace and __autoload as you see: in folder b\\b.php :

<?php          
namespace b;
use b as x;

function __autoload($clsName){
  $clsName='../'.str_replace('\\', '/', $clsName).'.php';
  require_once $clsName;
}
class b{
  function __construct(){
    print("b file<hr/>");
  }
}
$t=new x\c(); // line 13 
?>

and in folder b\\c.php :

<?php
namespace b;

class c{
    function __construct(){
        print("c file<hr/>");
    }
}
?>

when we define $t=new x\\c , __autoload doesn't call! please help me :(

error message:

Fatal error: Class 'b\c' not found in C:\xampp\htdocs\project\TEST\b\b.php on line 13

You have not defined autoloader. PHP looks for __autoload (or \\__autoload - function defined in global namespace) while you have defined only \\b\\__autoload (yes, functions are namespaced to!)

How to fix it: move __autoload declaration outside namespace

Better fix: you should use spl_autoload_register

It's hard to see exactly what is going wrong. By the looks of the error, it appears that the __autoload() function isn't being called. If it was I would expect the require_once statement to fail with an error saying file not found, or something like that.

You could try by putting some debugging statements in your __autoload() function to see what's going on, including a var_dump of your $clsName variable.

It might be worth noting the following message that appears in the PHP manual regarding autoloading :

spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

You should also note, that there is a "standard" for PHP autoloading, called PSR-0 . Here is a link to an article that gives a good explanation of it.

In both the article and the PSR-0 document mentioned above, are example autoloaders that you can use. I would suggest using one of these than trying to implement your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM