Php 用父对象构造子类是一种不好的做法吗?
我有一个搜索类,我正在使用它从两个不同的来源获取结果并将它们组合在一起。搜索类是父类,有两个子类A和B,它们扩展了搜索 在Search类中,我有一个名为fetch()的方法,该方法实例化两个子对象以获取结果。它看起来像这样:Php 用父对象构造子类是一种不好的做法吗?,php,oop,class,parent-child,Php,Oop,Class,Parent Child,我有一个搜索类,我正在使用它从两个不同的来源获取结果并将它们组合在一起。搜索类是父类,有两个子类A和B,它们扩展了搜索 在Search类中,我有一个名为fetch()的方法,该方法实例化两个子对象以获取结果。它看起来像这样: public function fetch(){ $a = new A($this); $a_results = $a->fetch(); $b = new B($this); $b_results = $b->fetch(); // c
public function fetch(){
$a = new A($this);
$a_results = $a->fetch();
$b = new B($this);
$b_results = $b->fetch();
// code to combine the results here
}
class A extends Search
{
public function __construct(Search $search){
parent::__construct($search->category, $search->offset, $search->keywords...);
}
A类和B类的构造函数都是这样的:
public function fetch(){
$a = new A($this);
$a_results = $a->fetch();
$b = new B($this);
$b_results = $b->fetch();
// code to combine the results here
}
class A extends Search
{
public function __construct(Search $search){
parent::__construct($search->category, $search->offset, $search->keywords...);
}
感觉好像我做错了什么,因为我将父对象传递给子对象,然后创建另一个具有完全相同数据的父对象。有没有更好的方法来设置这个
我之所以这样设置,是因为我的应用程序的某些部分需要直接访问类A和B,而不是通过父搜索类。使用组合,例如让搜索类拥有一个源数组,其中,每个源都是源类的实例,您可以在其中定义源的公共项,并传递每个a和B源的参数 如果不清楚的话,这里的想法是让源类返回源中的数据,并让搜索类进行搜索。这是否实用或有效取决于实际的搜索来源和方式
class Search {
private $sources = array();
public Search($p1,$p2,$p3,$p4) {
//Use proper parameters to define the sources
$sources[] = new Source("A",$p1,$p2,$p3,$p4);
$sources[] = new Source("B",$p1,$p2,$p3,$p4);
}
public function fetch() {
foreach ($source in $sources) {
$results[] = $source->fetch();
}
combine($results);
}
}
class Source {
//Whatever you need to define the source
public function fetch() {
//Fetch from the proper source
}
public Source($name,$p1,$p2,$p3,$p4) {
//Store the parameters to be able to operate
}
}
A和B都实现了fetch方法吗?否则,这将导致无限循环。似乎扩展搜索并不是您真正想要的,相反,A和B类应该简单地将搜索对象作为其_构造参数来使用搜索对象的属性。是的,A和B都有fetch()方法,它们具有不同的逻辑。也许,A和B不需要扩展搜索,但它们使用构造对象所需的相同成员和相同方法,因此,对我来说,它们扩展搜索是有意义的。你是对的,以这种方式扩展搜索类是毫无意义的。我只需要传递搜索对象,然后访问它的属性。如果你把它写在答案中,我可以把它标记为可接受的解决方案。