Search code examples
phpspl-autoload-registerspl-autoload-call

Fatal error with spl_autoload


I have this piece of code here to load classes automatically:

<?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();

But i allways get the following error:
Fatal error: spl_autoload(): Class StreamFactory could not be loaded in C:\Users\Test\PhpstormProjects\Test\test.php on line 24

When i check the paths that get set in the include path, they are correct.
Can someone give me a hint, why that error gets thrown?


Solution

  • You need to change the name of StreamFactory class to stream_factory and instantiate it with $streamFactory = new stream_factory(); or rename the file 'stream_factory.class.php' to 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__;
      }
    }