我基本上有以下目录结构
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/