Skip to content
Advertisement

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 MesProduitsProduit;

or

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

But the code below failed:

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

or

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

Advertisement

Answer

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 MesProduitsProduit;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement