spl_autoload发生致命错误

时间:2016-02-14 23:30:52

标签: php spl-autoload-register spl-autoload-call

我这里有一段代码可以自动加载类:

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

但我总是得到以下错误:
致命错误:spl_autoload():无法在第24行的C:\ Users \ Test \ PhpstormProjects \ Test \ test.php中加载类StreamFactory

当我检查在包含路径中设置的路径时,它们是正确的 有人可以给我一个提示,为什么会抛出这个错误?

1 个答案:

答案 0 :(得分:1)

您需要将StreamFactory类的名称更改为stream_factory并使用$streamFactory = new stream_factory();对其进行实例化,或将文件'stream_factory.class.php'重命名为StreamFactory.class.php。< / p>

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__;
  }
}