假设这些在单独的文件中。
<?php
namespace aName;
function importerLoader($class)
{
$elements = explode('\\',$class);
if (count($elements) == 2 && $elements[0] == __NAMESPACE__)
{
$filename = $elements[1].'.php';
if (file_exists($filename) )
{
error_log("calling".$filename);
require($filename);
}
else
{
error_log("File does not exist ".$filename);
return false;
}
}
}
spl_autoload_register(__NAMESPACE__.'\importerLoader');
<?php
namespace aName;
class Question
{
...
protected function importAnswers()
{
foreach($this->QuestionData as $answer)
{
$this->answerObjects[$index] = new Answer($answer);//Fatal error
also tried
$this->answerObjects[$index] = new Answer::answerFactory($answer);//Fatal error
}
}
...
public static function questionFactory($question)
{
$returnMe = false;
if (self::validQuestionType($question))
{
switch ($question[0]->qtid)
{
case 1:
$returnMe = new QuestionType1($question);
break;
case 2:
$returnMe = new QuestionType2($question);
break;
}
return $returnMe;
}
}
}
<?php
namespace aName;
class Answer
{
...
public static function answerFactory($answer)
{
$returnMe = false;
switch ($answer->qtid)
{
case 1:
$returnMe = new AnswerType1($answer);
break;
case 2:
$returnMe = new AnswerType2($answer);
break;
default:
$returnMe = new Answer($answer);
break;
}
return $returnMe;
}
}
最后
<?php
namespace aName;
class Quiz
{
...
function importQuestion($question)
{
//insert newly created into it's proper ordering int he question objects table.
$this->_questionObjects[$question[0]->question_order] = Question::questionFactory($question);
}
}
注意:自动加载器适用于所有其他类。Answer.php 类没有。我得到一个致命错误。我检查了错别字。它都在同一个目录中。当 Quiz 导入问题时,工厂工作。但是当问题得到答案时,我得到一个致命错误。请注意,测验是自动加载器调用的另一个对象中的一个对象。
我明白了
PHP Fatal error: Class 'aName\Answer' not found in C:\<A PATH>\Question.php on line 315
我彻底迷路了。它甚至包含该文件,但它不识别该类。我只能猜测这是一个命名空间问题,但我无法弄清楚它是什么。