2016-11-13 50 views
0

問題?自動加載器問題沒有返回類

Bootloader(Autoloader)似乎沒有正常工作,或者我錯過了一些東西。這是簡化的代碼。

下面的代碼返回

類 「骨架」 不存在。

在index.php文件中。

的index.php

<?php 

include 'bootloader.php'; 
use Skeleton\Html\LoginHeader; 
$tool = new Skeleton/Html/LoginHeader(); 

bootloader.php

<?php 

function Boot($className) { 
     $fileName = ''; 
     $namespace = ''; 

     // Sets the include path as the "src" directory 
     $includePath = dirname(__FILE__).DIRECTORY_SEPARATOR.'src'; 

     if (false !== ($lastNsPos = strripos($className, '\\'))) { 
      $namespace = substr($className, 0, $lastNsPos); 
      $className = substr($className, $lastNsPos + 1); 
      $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; 
     } 
     $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; 
     $fullFileName = $includePath . DIRECTORY_SEPARATOR . $fileName; 

     if (file_exists($fullFileName)) { 
      require $fullFileName; 
     } else { 
      echo 'Class "'.$className.'" does not exist.'; 
     } 
    } 
    spl_autoload_register('Boot'); // Registers the autoloader 

的src /骨架/ HTML/LoginHeader.php

<?php 

namespace Skeleton\Html; 

class LoginHeader() { 
    echo "<h1>Login Header OK!</h1>"; 
} 

回答

1

一對夫婦的問題在這裏:

1)這條線/部分是不正確的:

class LoginHeader() { 

應該是:

class LoginHeader 
    { 
     public function __construct() 
      { 
       echo "<h1>Login Header OK!</h1>"; 
       ...etc 

2)您沒有正確地分配你的類。您有:

$tool = new Skeleton/Html/LoginHeader(); 

應該是反斜線:

  --------v----v 
$tool = new Skeleton\Html\LoginHeader(); 

一旦你解決您的反斜線,你會得到一個語法錯誤的類頁中指出,但磁帶自動加載機本身工作正常。