Pass parameters to the constructor as opposed to methods other than the constructor?
I'm new to OOP and just wanted to know, within a class, when should you pass parameters to the constructor as opposed to methods other than the constructor?
Example where parameters are passed to the con开发者_C百科structor
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
Example where parameters are passed to a method other than constructor
(Credit to Geoff Adams who wrote this out in a previous question I asked)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
I think you question is incorrect because it depends on the purpose of the class and your example is very abstract. But in common you shouldn't do any actions in constructor except initialization and yes it's better to pass initial data to constructor. Another approach is to use setters' methods. Anyway I think it's better for the first variant you should use class with structure:
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;
}
}
There's no rule. It depends on how you're going to use the class. You can even do it both ways within the same class.
精彩评论