2016-02-14 2 views
2

J'ai ce morceau de code ici pour charger automatiquement des classes:Erreur fatale avec spl_autoload

<?php 
$test = [ 
      'includeDirs' => [ 
       'interfacesDir' => __DIR__ . DIRECTORY_SEPARATOR . 'interfaces'. DIRECTORY_SEPARATOR, 
       'abstractsDir' => __DIR__ . DIRECTORY_SEPARATOR . 'abstracts'. DIRECTORY_SEPARATOR, 
       'classesDir' => __DIR__ . DIRECTORY_SEPARATOR . 'classes'. DIRECTORY_SEPARATOR 
      ], 
      'includeExtensions' => [ 
       'classExtension' => '.class.php', 
       'abstractExtension' => '.abstract.php', 
       'interfaceExtension' => '.interface.php' 
      ] 
     ]; 

set_include_path('.'); 
set_include_path(get_include_path() . PATH_SEPARATOR . implode(PATH_SEPARATOR, $test['includeDirs'])); 

spl_autoload_extensions(implode(',', $test['includeExtensions'])); 
spl_autoload_register(); 

$streamFactory = new StreamFactory(); 

Mais je Allways obtenir l'erreur suivante:
Erreur fatale: spl_autoload(): ne peut pas être chargé de classe StreamFactory dans C: \ Utilisateurs \ Test \ PhpstormProjects \ Test \ test.php sur la ligne 24

Lorsque je vérifie les chemins qui sont définis dans le chemin d'inclusion, ils sont corrects.
Quelqu'un peut-il me donner un indice, pourquoi cette erreur est-elle lancée?

+0

Où se trouve l'emplacement de la classe StreamFactory? c'est «classes»? –

+0

Oui c'est ici: C: \ Utilisateurs \ Test \ PhpstormProjects \ Test \ classes \ stream_factory.class.php –

+0

Encore une question, quel est l'espace de noms utilisé par StreamFactory? –

Répondre

1

Vous devez changer le nom de StreamFactory classe à stream_factory et instancier avec $streamFactory = new stream_factory(); ou renommer le fichier « stream_factory.class.php » à StreamFactory.class.php.

index.php

<?php 

error_reporting(-1); 
ini_set('display_errors', 'On'); 

$test = [ 
    'includeDirs' => [ 
    'interfacesDir' => __DIR__ . DIRECTORY_SEPARATOR . 'interfaces'. DIRECTORY_SEPARATOR, 
    'abstractsDir' => __DIR__ . DIRECTORY_SEPARATOR . 'abstracts'. DIRECTORY_SEPARATOR, 
    'classesDir' => __DIR__ . DIRECTORY_SEPARATOR . 'classes'. DIRECTORY_SEPARATOR 
    ], 
    'includeExtensions' => [ 
    'classExtension' => '.class.php', 
    'abstractExtension' => '.abstract.php', 
    'interfaceExtension' => '.interface.php' 
    ] 
]; 

set_include_path('.'); 
set_include_path(get_include_path() . PATH_SEPARATOR . implode(PATH_SEPARATOR, $test['includeDirs'])); 

spl_autoload_extensions(implode(',', $test['includeExtensions'])); 
spl_autoload_register(); 

try { 
    $streamFactory = new \stream_factory(); 
} catch(Exception $e) { 
    echo $e->getMessage(); 
} 

classes/stream_factory.class.php

<?php 
class stream_factory { 
    function __construct() { 
    echo "Hello from " . __CLASS__; 
    } 
}