Search code examples
phpspl-autoload-register

The 'include' of 'spl_autoload_register' can't find the path


I can use a class with include and use but I failed with spl_autoload_register.

I tried different methods without success.

What's work fine:

include "MesProduits/Produit.php";
use MesProduits\Produit;

or

function monAutoLoad() {
    include "MesProduits/Produit.php";
} 
spl_autoload_register('monAutoload'); 
use MesProduits\Produit;

But the code below failed:

function monAutoLoad($class) { 
    include  "MesProduits/" . $class . ".php"; 
} 
spl_autoload_register('monAutoload');
use MesProduits\Produit;

or

spl_autoload_register(function ($class) {
    include 'MesProduits/' . $class . '.php';
});
use MesProduits\Produit;

Solution

  • The problem was that use needs backslash for the spacename and include needs slash for the path of the file.php where I have the classes. I'm on MacOS X and I read using a Mac generates this kind of problem.

    The solution was using a str_replace to convert \ in /.

    function monAutoLoad($class) {
        include(str_replace("\\", "/", $class). ".php");
    }
    
    spl_autoload_register('monAutoLoad');
    
    use MesProduits\Produit;