我有一个类,该类具有从数据库检索子元素的功能。下面的代码将是伪伪的,因为我想使其尽可能简单。
abstract class SomeHostObject extends SomeObject {
function getChild($identifier) {
global $database;
$id = $database->select('Some MySQL Query');
// that is the problem
return ?new? ???($id);
}
}
如您所见,类
SomeHostObject
是抽象的,必须进行扩展。问题是,
getChild()
不应返回SomeHostObject
实例(不仅因为它甚至无法实例化),而且还应返回扩展SomeHostObject
的类的新实例。例如,如果存在扩展了
PageObject
的类SomeHostObject
,则函数getChild()
应该返回具有新ID的新PageObject
实例。我不知道是否将此问题称为“高级”,但对我而言,这是一个重大问题。
最佳答案
abstract class SomeHostObject extends SomeObject {
function getChild($identifier) {
global $database;
$id = $database->select('Some MySQL Query');
// that is the problem
return $this->createObject($id);
}
abstract protected function createObject($id);
}
class PageObject extends SomeHostObject
{
protected function createObject($id)
{
return new PageObject($id);
}
}