伙计我使用spl_autoload_register
功能遇到问题。我在其XAMPP
目录中htdocs
使用的是另一个名为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
Code 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 :(得分: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