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

use*_*149 0 php namespaces php-5.5

我基本上有以下目录结构

  • 迷你履带车
    • 脚本/
      • htmlCrawler.php
    • 索引.php

这是index.php

use Scripts\htmlCrawler;

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

$main = new Main();
$main->init();
Run Code Online (Sandbox Code Playgroud)

这是 /Scripts/htmlCrawler.php

namespace Scripts;

    class htmlCrawler
    {
        public function sayHello()
        {
            return 'sfs';
        }
    }
Run Code Online (Sandbox Code Playgroud)

代码抛出以下错误

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

Ant*_*neB 7

您忘记将该文件包含/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();
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 还可以建议“composer”来处理自动加载 (3认同)