我的项目结构如下:
init.php
我的脚本<?php
use Bookstore\Domain\Book;
use Bookstore\Domain\Customer;
function autoloader($classname) {
$lastSlash = strpos($classname, '\\') + 1;
$classname = substr($classname, $lastSlash);
$directory = str_replace('\\', '/', $classname);
$filename = __DIR__ . '/src/' . $directory . '.php';
require_once($filename);
}
spl_autoload_register('autoloader');
$basic = new Basic(1, "name", "surname", "email");
$premium = new Premium(2, "name", "surname", "email");
var_dump($basic);
var_dump($premium);
包含以下内容:
(...)
"autoload": {
"psr-4": {
"AppBundle\\": "src/AppBundle",
"CoreBundle\\": "src/CoreBundle"
},
(...)
我的错误是:
PHP警告:require_once(/srv/http/libro_php7/src/asic.php):无法打开流:第11行/srv/http/libro_php7/init.php中没有此类文件或目录 PHP致命错误:require_once():无法打开所需&#39; /srv/http/libro_php7/src/asic.php'第11行/srv/http/libro_php7/init.php中的(include_path =&#39;。:&#39;)
谢谢!
答案 0 :(得分:0)
首先,您应该调整自动加载器以忽略不在Bookstore
命名空间内的类名,并将其简化为:
function autoloader($classname) {
/**
* only handle classnames starting with "Bookstore\"
*/
if (0 === strpos($className, 'Bookstore\\')) {
$filename = __DIR__ . '/src/' . str_replace('\\', '/', $className) . '.php';
require_once $filename;
}
}
其次,您缺少导入(这就是自动加载器无法正确找到您的类的原因
Bookstore\Domain\Customer\Basic
Bookstore\Domain\Customer\Premium
(事件没有这么做,在创建实例之前就失败了)<?php
use Bookstore\Domain\Book;
use Bookstore\Domain\Customer\Basic;
use Bookstore\Domain\Customer\Premium;
// see definition above
spl_autoload_register('autoloader');
$basic = new Basic(1, "name", "surname", "email");
$premium = new Premium(2, "name", "surname", "email");
var_dump($basic);
var_dump($premium);
<?php
use Bookstore\Domain\Book;
use Bookstore\Domain\Customer;
// see definition above
spl_autoload_register('autoloader');
$basic = new Customer\Basic(1, "name", "surname", "email");
$premium = new Customer\Premium(2, "name", "surname", "email");
var_dump($basic);
var_dump($premium);