将参数传递给构造函数,而不是传递给构造函数以外的方法


Pass parameters to the constructor as opposed to methods other than the constructor?

我是OOP的新手,只是想知道,在类中,何时应该将参数传递给构造函数而不是构造函数以外的方法?

参数传递给构造函数的示例
class Foo {
    public function __construct($a, $b, $c) {
        $this->sum = $a + $b + $c;
    }
    public function display(){
        echo $this->sum;
    }
}
$foo = new Foo(1,2,3);
echo $foo->display(); //Displays 6

参数传递给构造函数以外的方法的例子

(归功于Geoff Adams,他在之前的问题中写了这一点)
class Foo {
    public function sum($a, $b, $c) {
        $sum = $a + $b + $c;
        return $sum;
    }
}
$foo = new Foo();
echo $foo->sum(1,2,3); //Displays 6

我认为你的问题是不正确的,因为它取决于类的目的,你的例子是非常抽象的。但通常你不应该在构造函数中做任何动作,除了初始化,是的,最好将初始数据传递给构造函数。另一种方法是使用setter的方法。无论如何,我认为这是更好的第一个变体你应该使用类与结构:

class Foo {
    private $a = 0;
    private $b = 0;
    private $c = 0;
    private $sum = null;
    public function __construct($a, $b, $c) {
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;
    }
    public function sum()
    {
         $this->sum = $this->a+$this->b+$this->c;
    }
    public function display(){
        if (is_null($this->sum)) {
            $this->sum();
        }
        echo $this->sum;
    }
}

没有规则。这取决于你如何使用这个类。您甚至可以在同一个类中使用这两种方法。