【发布时间】:2016-04-08 20:22:26
【问题描述】:
这是第一次使用自动加载器并遇到一些错误。 结构如下:
- AnimalShop(根)
- 类
- Shop.php
- index.php
- 类
我有以下简单的代码
Index.php
<?php
spl_autoload_register(function ($class_name)
{
include $class_name . '.php';
});
echo "<h1>PETs SHOP</h1>";
// Create a shop
$shop = new Shop();
Shop 是一个简单的类
<?php
namespace PHPAdvanced\AnimalShop\classes;
/*
* Pet shop
*/
class Shop
{
/**
* @var Pets[] pets
*/
private $pets = [];
public function addPetsToArray(Pets $pet)
{
$this->pets[] = $pet;
}
/**
* Print pets naam
*/
public function printPets()
{
foreach($this->pets as $pet)
{
echo "<p>" . $pet->getPetNaam() . "</p>";
}
}
}
当我运行 index.php 时出现以下错误:
警告:include(Shop.php):无法打开流:第 4 行的 /var/www/ppadvancedCourse/AnimalShop/index.php 中没有这样的文件或目录
警告:include():无法在第 4 行的 /var/www/ppadvancedCourse/AnimalShop/index.php 中打开“Shop.php”以包含 (include_path='.:/usr/share/php:')
【问题讨论】:
-
是
shop.php位于/var/www/phpadvancedCourse/AnimalShop/吗? -
nvm 我在你的问题中看到了..
-
include 'classes/' . $class_name . '.php'; -
顺便说一句,这是一种使用命名空间和自动加载器的奇怪方式。你应该看看
PSR-0和PSR-4
标签: php namespaces autoload