何时使用方法vs在构造函数中设置属性?

时间:2017-08-30 09:24:09

标签: php oop

我是OOP的新手,为了方便起见,我不确定我应该在构造函数中设置属性,而不是只使用使用方法

选项1(方法):

tokens = request.GET.getlist('token')
# ...
with open(path) as input_data:
    for line in input_data:
        if 'visual' in tokens and line.startswith('2_visualid_'):
            prev_key = line.lstrip('2_visualid_').rstrip()
            data.update({prevkey: []})
            # you may want to continue to next line here - or not
            # continue

        if 'time' in tokens:
            if search_string in line and prev_key in data:            
                 data[prev_key].append(next(input_data).lstrip('2_mrslt_').rstrip())

然后我可以这样反过来:

class String {

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

    function reverse() {
        return str_reverse($this->word);
    }

}

选项2(属性):

$word = new String('potato');
echo $word->reverse();

然后我可以这样反过来:

class String {

    public $reverse;

    function __construct($word) {
        $this->word = $word;
        $this->reverse = $this->reverse();
    }

    function reverse() {
        return str_reverse($this->word);
    }

}

第二个选项看起来更好。

但是,我想知道是否一直有使用选项2 的任何陷阱?

1 个答案:

答案 0 :(得分:1)

TL;博士

您需要亲自了解哪种方法最适合您的背景。

值对象

以下是可能对您有意义的值对象示例:

  • 它保持状态
  • 这是不可改变的
  • 调用$word->reverse()返回值对象的新实例,但是使用反向字符串值
final class Word
{
    private $word;

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

    public function reverse(): self
    {
        return new self(strrev($this->word));
    }

    public function __toString()
    {
        return $this->word;
    }
}

$word = new Word('potato');

echo $word->reverse();

有关示例,请参阅:

服务

以下是服务的示例:

  • 它没有任何状态
  • 调用$service->reverse()需要传入单词,它会返回单词revers
final class Service
{
    public function reverse(string $word): string
    {
        return strrev($word);
    }
}

$service = new Service();

echo $service->reverse('potato');

有关示例,请参阅:

建议阅读