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

标签 php namespaces php-5.5

我基本上有以下目录结构

  • 迷你爬行器
  • 脚本/
  • htmlCrawler.php
  • index.php

  • This is the index.php


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

    And this is the /Scripts/htmlCrawler.php


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

    代码抛出以下错误

    Fatal error: Class 'Scripts\htmlCrawler' not found in /mnt/htdocs/Spielwiese/MiniCrawler/index.php on line 9

    最佳答案

    您忘记包含文件 /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 获得类似的功能。 .

    关于php - 为什么 PHP 在命名空间中找不到我的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38762591/

    相关文章:

    php - 如何左连接另一个嵌套表?

    php - 使用LIKE子句和NO_BACKSLASH_ESCAPES模式在mysqli prepare()中转义%号

    php - PHP MVC在本地工作,但是当上传到主机时失败

    php - MySQL/FPDF : How to limit the data by each page in PDF

    javascript - 调度名称中带有点的 CustomEvent 不会触发 jQuery.on() 事件监听器

    web-services - URI 命名空间和 WSDL 文件

    python - 避免 Python 中的模块命名空间污染

    php - 在 OS X 上的 PHP 5 上安装 OAuth PECL 包

    php - 在 Session 中设置用户 id 或用户名安全吗?

    audio - 以HTML5顺序播放音频文件