簡體   English   中英

PHP spl_autoload_register()不會使用命名空間打開文件

[英]PHP spl_autoload_register() doesn't open a file with namespace

伙計們,我使用spl_autoload_register函數spl_autoload_register了問題。 我正在使用的是htdocs目錄中的XAMPP ,還有另一個名為boot目錄。 該目錄有2個文件,一個Car class文件,一個Main php文件。 該類使用namespace boot 我想通過使用此函數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;

幾個例子:

目錄結構:

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 \\ Baz \\ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM