【问题标题】:Why does PHP not find my class within the namespace为什么 PHP 在命名空间中找不到我的类
【发布时间】:2016-08-04 08:46:33
【问题描述】:

我基本上有以下目录结构

  • 迷你爬虫
    • 脚本/
      • htmlCrawler.php
    • index.php

这是 index.php

use Scripts\htmlCrawler;

class Main
{
    public function init()
    {
        $htmlCrawler = new htmlCrawler();
        $htmlCrawler->sayHello();
    }
}

$main = new Main();
$main->init();

这是 /Scripts/htmlCrawler.php

namespace Scripts;

    class htmlCrawler
    {
        public function sayHello()
        {
            return 'sfs';
        }
    }

代码抛出如下错误

致命错误:在中找不到类 'Scripts\htmlCrawler' /mnt/htdocs/Spielwiese/MiniCrawler/index.php 第 9 行

【问题讨论】:

  • 您是否在index.php 文件中的任何位置包含/Scripts/htmlCrawler.php
  • @AntoineB 如果我使用 include('Scripts/htmlCrawler.php');但这不会破坏 use 语句的目的吗?例如 Symfony 类只使用 'use' 语句,而不包括 eachother 中的文件
  • 我在回答中详细说明了一切:)

标签: php namespaces php-5.5


【解决方案1】:

您忘记在您的index.php 文件中包含文件/Scripts/htmlCrawler.php

require_once "Scripts/htmlCrawler.php";

use Scripts\htmlCrawler;

class Main
{
    public function init()
    {
        $htmlCrawler = new htmlCrawler();
        $htmlCrawler->sayHello();
    }
}

$main = new Main();
$main->init();

如果您从未提供定义此类的文件,您的索引文件将找不到 htmlCrawler 文件的定义,并且命名空间的使用不会自动包含所需的类。

框架不需要您手动包含文件并且您可以简单地添加use 语句的原因是因为它们正在为开发人员处理所需类的包含。大多数框架都使用composer 来处理文件的自动包含。

您可以使用autoloading 获得类似的功能。

【讨论】:

  • 也可以建议composer 负责自动加载
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 2017-10-04
  • 2012-08-04
  • 2017-05-01
相关资源
最近更新 更多