如何处理多个构造函数参数或类变量? [英] How do i deal with multiple contructor arguments or class variables?

查看:76
本文介绍了如何处理多个构造函数参数或类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I know what to load in a constructor and what to set using the set methods later on?

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

For example, I have a question class which most of the time will call the following vars:

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

目前我已经拥有了,所以只有基本的必需品 $ id $ question $ content 已在构造函数中设置,因此我不会开始构建大量的构造函数参数。但是,这意味着当我在其他地方创建一个新的问题对象时,必须立即设置该对象的其他属性,因为这意味着设置者代码在所有地方都被复制。

At the moment I have it so only the bare essentials $id, $question, and $content are set in the constructor so I don't start building up a huge list of constructor arguments. This however, means that when I make a new question object elsewhere, I have to set the other properties of that object straight after meaning 'setter code' getting duplicated all over the place.

我应该立即将它们全部传递到构造函数中,还是按照我已经使用的方式进行传递,还是缺少一个更好的解决方案?谢谢。

Should I just pass them all into the constructor right away, do it the way I'm doing it already, or is there a better solution that I'm missing? Thanks.

推荐答案

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

A fluent interface is another solution.

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;
  }

  ...
}

或使用可选参数...

Or use optional parameters...

class Foo {
  protected $stuff;
  protected $moreStuff;

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

  ...
}

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

In any case, there are many good solutions. Please dont use a single array as params or func_get_args or _get/_set/__call magic, unless you have a really good reason to do so, and have exhausted all other options.

这篇关于如何处理多个构造函数参数或类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆