为什么PHP没有在命名空间中找到我的类

时间:2016-08-04 08:46:34

标签: php namespaces php-5.5

我基本上有以下目录结构

  • MiniCrawler
    • 脚本/
      • 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'   第9行/mnt/htdocs/Spielwiese/MiniCrawler/index.php

1 个答案:

答案 0 :(得分:3)

您忘记将文件/Scripts/htmlCrawler.php包含在index.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获得一些类似的功能。