2017-09-13 57 views
1

夥計們我使用spl_autoload_register函數面臨問題。我使用的是XAMPP在其htdocs目錄中有另一個名爲boot的目錄。該目錄有2個文件,一個Car class文件和一個Main php文件。該班使用namespaceboot。我想通過使用此功能加載該類spl_autoload_register,但錯誤即將出現。我做錯了什麼。PHP spl_autoload_register()不打開名稱空間的文件

Warning: require(boot\Car.php): failed to open stream: No such file or directory in C:\xampp\htdocs\boot\Main.php

代碼Car.php

<?php 
namespace boot; 

class Car 
{ 

    public function __construct() 
    { 
     echo 'Constructor has been created!'; 
    } 
} 

代碼Main.php

<?php 
spl_autoload_register(function ($className){ 
    require $className . '.php'; 
}); 

use boot\Car; 
$car = new Car; 
+0

可以你確認'C:\ xampp \ ht docs \ boot \ Main.php'是確切的路徑? – Thamaraiselvam

+0

可能重複的[PHP - 無法打開流:沒有這樣的文件或目錄](https://stackoverflow.com/questions/36577020/php-failed-to-open-stream-no-such-file-or- directory ) – Thamaraiselvam

+0

@Thamaraiselvam是 –

回答

0

幾個例子:

目錄結構:

project folder 
- Main.php 
- Car.php 
- Test.php 
- Foo 
- - Bar.php 
- - Baz 
- - - Qux.php 

test.php的

class Test {} 

富\ Bar.php

namespace boot\Foo; 
class Bar {} 

富\巴茲\ Qux.php

namespace Foo\Baz; 
class Qux {} 

Main.php

//__DIR__ === C:\xampp\htdocs\boot  

spl_autoload_register(function ($className){ 
    //__DIR__ . DIRECTORY_SEPARATOR . 
    require_once preg_replace('/^[\\\\\/]?boot[\\\\\/]?/', '', $className). '.php'; 
}); 

// both require same file but namespace must be same as defined in file 
$t = new boot\Car; // work 
$t = new Car; // do not work because in Car.php is namespace `boot` 
// required file: C:\xampp\htdocs\boot\Car.php 

// both require same file but namespace must be same as defined in file 
$t = new boot\Test; // do not work because in Test.php is no namespace 
$t = new Test; //work 
// required file: C:\xampp\htdocs\boot\Test.php 

// both require same file but namespace must be same as defined in file 
$t = new boot\Foo\Bar; // work 
$t = new Foo\Bar; // do not work because in Bar.php is namespace `boot\Foo` 
// required file: C:\xampp\htdocs\boot\Foo\Bar.php 

// both require same file but namespace must be same as defined in file 
$t = new boot\Foo\Baz\Qux; // do not work because in Qux.php is namespace `Foo\Baz` 
$t = new Foo\Baz\Qux; // work 
// required file: C:\xampp\htdocs\boot\Foo\Baz\Qux.php 
相關問題