PHP自动加载器不使用命名空间

时间:2016-04-08 20:22:27

标签: php namespaces autoload

它是第一次使用自动加载器并出现一些错误。 结构如下:

  • AnimalShop(root)
      • 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();

商店是一个简单的课程

<?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>

2 个答案:

答案 0 :(得分:0)

spl_autoload_register(function ($class_name) 
{
    include realpath(dirname(__FILE__))."/classes/".$class_name . '.php';
});

你的路径错了..试试这个......

答案 1 :(得分:0)

为了解决这个问题,我使用PSR-4通过作曲家自动加载以下结构和代码。

<强>结构

  • AnimalShop(root)
    • index.php
    • App(文件夹)
      • 行为(文件夹)
        • WalkBehavior.php(界面)
      • 宠物(文件夹)
        • Cat.php
        • Dog.php
        • Fish.php
        • Pets.php(抽象类)
      • 商店(文件夹)
        • PetShop.php

<强> 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>";
        }
    }
}