为什么 PHP 在命名空间中找不到我的 class
Why does PHP not find my class within the namespace
我基本上有以下目录结构
- 迷你爬虫
- 脚本/
- 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();
如果您从未提供定义此 class 的文件,则您的索引文件无法找到 htmlCrawler
文件的定义,并且命名空间的使用不会自动包含所需的 classes.
框架不要求您手动包含文件而您只需添加 use
语句的原因是因为它们正在为开发人员处理包含所需的 classes .大多数框架都使用 composer 来处理文件的自动包含。
您可以使用 autoloading 获得类似的功能。
我基本上有以下目录结构
- 迷你爬虫
- 脚本/
- 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();
如果您从未提供定义此 class 的文件,则您的索引文件无法找到 htmlCrawler
文件的定义,并且命名空间的使用不会自动包含所需的 classes.
框架不要求您手动包含文件而您只需添加 use
语句的原因是因为它们正在为开发人员处理包含所需的 classes .大多数框架都使用 composer 来处理文件的自动包含。
您可以使用 autoloading 获得类似的功能。