我是PHP OOP的新手,我似乎无法正确地获取我的类文件。每当我试图要求它们时,我都会遇到致命的错误。此外,phpstorm说我的类是未定义的。位置路径显示为有效,因为phpstorm没有说找不到路径。但是在运行时无法找到类。
ToyPlansV1.0 / TestMain.php - >该类调用Test类的setup ToyPlansV1.0 / includes / DatabaseHandler.php - >要测试的底层类 ToyPlansV1.0 / includes / TestClasses / DBHandlerTest.php - >这个类是Test类
TestMain.php的内容
<?php
require ("includes/TestClasses/DBHandlerTest.php");
$DBTest = new DBHandlerTest();
$DBTest.Setup();
?>
DBHandlerTest.php的内容
<?php
namespace includes\TestClasses;
require("../DatabaseHandler.php");
class DBHandlerTest {
protected $DB;
protected function Setup(){
$this->$DB = new DatabaseHandler();
}
}
运行TestMain.php时遇到的错误是:
require(../ DatabaseHandler.php):无法打开流:第3行的C:\ wamp \ www \ ToyPlansV1.0 \包含\ TestClasses \ DBHandlerTest.php中没有此类文件或目录
致命错误:require():在C:\ wamp \ www \ ToyPlansV1.0 \ includes \ TestClasses中打开所需的'../DatabaseHandler.php'(include_path ='。; C:\ php \ pear')失败第3行的DBHandlerTest.php
PHP致命错误:require():在C:\ wamp \ www \ ToyPlansV1.0 \ includes \中打开所需的'../DatabaseHandler.php'(include_path ='。; C:\ php \ pear')失败第3行的TestClasses \ DBHandlerTest.php
我出错的任何想法/如何修复需求路径?
编辑更新的代码,几乎正常工作。
<?php
//require ("includes/TestClasses/DBHandlerTest.php");
require(__DIR__.'/includes/TestClasses/DBHandlerTest.php');
use includes\TestClasses\DBHandlerTest As DBHandlerTest;
$DBTest = new DBHandlerTest();
$DBTest.Setup();
?>
<?php
namespace includes\TestClasses;
require(__DIR__.'/../DatabaseHandler.php');
use includes\DatabaseHandler As DatabaseHandler;
class DBHandlerTest
{
protected $DB;
public function Setup()
{
$this->$DB = new DatabaseHandler();
}
}
答案 0 :(得分:0)
在TestMain.php中,您必须使用DBHandlerTest
这样的use
课程声明:
require (__DIR__.'/includes/TestClasses/DBHandlerTest.php');
use includes\TestClasses\DBHandlerTest As DBHandlerTest;
$DBTest = new DBHandlerTest();
$DBTest->Setup();
在DBHandlerTest.php中,您必须使用Setup()
方法public
:
namespace includes\TestClasses;
require(__DIR__.'/../DatabaseHandler.php');
class DBHandlerTest
{
protected $DB;
public function Setup()
{
$this->$DB = new DatabaseHandler();
}
}
这样可行,但除此之外,您应该使用spl_autoload_register。它会让你的生活更轻松。