【问题标题】:PHP - Composer Autoload - Class not foundPHP - 作曲家自动加载 - 找不到类
【发布时间】:2019-05-16 07:36:44
【问题描述】:

我在通过 composer 使用自动加载的类时遇到问题。

这是我的文件结构:

-cache
-public
-src
--Repository
---PostRepository.php
-index.php
-composer.json

我正在尝试在 index.php 中加载 PostRepository.php。 但是报错

致命错误:未捕获的错误:类 'App\Repository\PostRepository' 不是 在 /opt/lampp/htdocs/index.php:12 中找到堆栈跟踪:#0 {main} throw 在第 12 行的 /opt/lampp/htdocs/index.php 中

这是我的 composer.json:

{
  "require": {
    "twig/twig": "^2.0"
  },

  "autoload": {
    "psr-4":  {
      "App\\" : "src/"
    }
  }
}

这是我的 PostRepository.php

<?php
namespace App\Repository;

class PostRepository
{
    ...
}

这是我的 index.php

<?php
require __DIR__ . "/vendor/autoload.php";

use App\Repository\PostRepository;

$postClass = new PostRepository();
$posts = $postClass->getAllPosts();

var_dump($posts);

看起来命名空间没问题。有什么问题?

【问题讨论】:

  • 根据您的粘贴,第 12 行出现错误。但是发布的 index.php 只有 9 行。

标签: php


【解决方案1】:

您应该在使用任何类之前包含 autoload.php。

试着让你的代码像这样:

<?php

require __DIR__ . "/vendor/autoload.php";

use App\Repository\PostRepository;
$postClass = new PostRepository();
$posts = $postClass->getAllPosts();

var_dump($posts);

然后做

composer dump-autoload

致命错误:未捕获的错误:类 'App\Repository\PostRepository' 不是 在 /opt/lampp/htdocs/index.php:12 中找到堆栈跟踪:#0 {main} throw 在第 12 行的 /opt/lampp/htdocs/index.php 中

htdocs/index.php !!您在 htdocs 中有一个项目吗? 因为你应该引用htdocs/your-project-folder/index.php

【讨论】:

  • 谢谢,但我试过这个,但得到了同样的错误。
  • 您是否在正确的文件夹中引用了正确的索引?
  • 哦,我的...你是对的,项目在我的本地主机上的错误目录...谢谢
猜你喜欢
  • 2018-10-01
  • 2016-03-06
  • 2014-08-15
  • 2014-02-11
  • 2014-04-24
  • 2017-01-02
  • 2019-01-31
相关资源
最近更新 更多