我如何处理多个构造函数参数或类变量?

时间:2013-02-18 13:26:10

标签: php oop constructor

我如何知道在构造函数中加载什么以及稍后使用set方法设置什么?

例如,我有一个问题类,大部分时间都会调用以下变量:

protected $question;
protected $content;
protected $creator;
protected $date_added;
protected $id;
protected $category;

目前我已经拥有它,所以在构造函数中只设置了基本要素$id$question$content所以我不会开始构建庞大的构造函数列表参数。然而,这意味着当我在其他地方创建一个新的问题对象时,我必须直接设置该对象的其他属性,意思是“setter代码”在整个地方重复。

我是否应该立即将它们全部传递给构造函数,按照我已经这样做的方式进行,或者是否有一个我错过的更好的解决方案?感谢。

5 个答案:

答案 0 :(得分:0)

根据语言的不同,任何一个类都可以有多个构造函数。

答案 1 :(得分:0)

您可以使用数组作为构造函数或setter方法的参数。

只是示例:

public function __construct($attributes = array()) {
  $this->setAttributes($attributes);
}  

public function setAttributes($attributes = array()) {
  foreach ($attributes as $key => $value) {
    $this->{$key} = $value;
  }
}

答案 2 :(得分:0)

PHP不支持传统的构造函数重载(与其他OO语言一样)。一个选项是将一组参数传递给构造函数:

public function __construct($params)
{

}

// calling it
$arr = array(
    'question' => 'some question',
    'content' => ' some content'
    ...
);
$q = new Question($arr);

使用它,您可以自由地传递可变数量的参数,并且不依赖于参数的顺序。同样在构造函数中,您可以设置默认值,因此如果不存在变量,请使用默认值。

答案 3 :(得分:0)

流畅的界面是另一种解决方案。

class Foo {
  protected $question;
  protected $content;
  protected $creator;
  ...

  public function setQuestion($value) {
    $this->question = $value;
    return $this;
  }

  public function setContent($value) {
    $this->content = $value;
    return $this;
  }

  public function setCreator($value) {
    $this->creator = $value;
    return $this;
  }

  ...
}

$bar = new Foo();
$bar
  ->setQuestion('something')
  ->setContent('something else')
  ->setCreator('someone');

或使用继承......

class Foo {
  protected $stuff;

  public function __construct($stuff) {
    $this->stuff = $stuff;
  }

  ...
 }

class bar extends Foo {
  protected $moreStuff;

  public function __construct($stuff, $moreStuff) {
    parent::__construct($stuff);
    $this->moreStuff = $moreStuff;
  }

  ...
}

或使用可选参数......

class Foo {
  protected $stuff;
  protected $moreStuff;

  public function __construct($stuff, $moreStuff = null) {
    $this->stuff = $stuff;
    $this->moreStuff = $moreStuff;
  }

  ...
}

无论如何,有很多好的解决方案。请不要使用单个数组作为params或func_get_args或_ get / _set / __ call magic,除非你有充分的理由这样做,并且已经用尽所有其他选项。

答案 4 :(得分:0)

我会使用我想要设置的值将数组传递给构造函数。

public function __construct(array $values = null)
{
    if (is_array($values)) {
        $this->setValues($values);
    }
}

然后你需要一个方法setValues来动态设置值。

public function setValues(array $values)
{
    $methods = get_class_methods($this);
    foreach ($values as $key => $value) {
        $method = 'set' . ucfirst($key);
        if (in_array($method, $methods)) {
            $this->$method($value);
        }
    }
    return $this;
}

为此,您需要为setQuestion($value)等属性设置setter方法。

相关问题