它是第一次使用自动加载器并出现一些错误。 结构如下:
我有以下简单代码
的index.php
<?php
spl_autoload_register(function ($class_name)
{
include $class_name . '.php';
});
echo "<h1>PETs SHOP</h1>";
// Create a shop
$shop = new 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/phpadvancedCourse/AnimalShop/index.php中没有此类文件或目录
警告:include():在第4行的/var/www/phpadvancedCourse/AnimalShop/index.php中打开包含(include_path ='。:/ usr / share / php:')的'Shop.php'失败< / p>
答案 0 :(得分:0)
spl_autoload_register(function ($class_name)
{
include realpath(dirname(__FILE__))."/classes/".$class_name . '.php';
});
你的路径错了..试试这个......
答案 1 :(得分:0)
为了解决这个问题,我使用PSR-4通过作曲家自动加载以下结构和代码。
<强>结构强>
<强> Composer.json 强>
MyString
MyString
MyString
MyString
MyString
<强>的index.php 强>
{
"autoload" : {
"psr-4" : {
"App\\" : "App"
}
}
}
Petshop and Dog的例子
<?php
// Autoload
require "vendor/autoload.php";
use App\Shop\PetShop;
use App\Pets\Dog;
use App\Pets\Fish;
use App\Pets\Cat;
echo "<h1>PETs SHOP</h1>";
// Create a shop
$shop = new PetShop();
$shop->addPetsToArray(new Dog("Yuki"));
$shop->addPetsToArray(new Fish("BLubie"));
$shop->addPetsToArray(new Cat("Cattie"));
$shop->printPets();
DOG
<?php
namespace App\Shop;
use App\Pets\Pets;
/*
* Pet shop
*/
class PetShop
{
/**
* @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>";
}
}
}