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 constructor
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: