2017-09-13 10 views
1

みんなspl_autoload_register関数を使って問題に直面しています。私が使用しているものは、そのhtdocsディレクトリにXAMPPであり、bootと呼ばれる別のディレクトリがあります。このディレクトリには、Car classというファイルとMainというphpファイルの2つのファイルがあります。そのクラスは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 {} 

はFoo \ Bar.php

namespace boot\Foo; 
class Bar {} 

はFoo \バズ\ 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 
関連する問題