0

I've started using OOP with PHP and constructed my variables in a way like this:

public $var;
public function setVar($var) {
    $this->var = $var;
}

Now i came across the magic function of __construct. If I understand this correctly you can use this function to achieve the same in a manner like this:

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

My question is the following: Is there a difference between these two methods? Which one is considered more clean and why? Also are there any pitfalls with my first method I'm not aware of?

  • Related: https://williamdurand.fr/2013/06/03/object-calisthenics/#9-no-getterssettersproperties – Your Common Sense Aug 04 '22 at 10:50
  • If you have all values when creating object - use constructor, otherwise you only left with setters/direct modification – Justinas Aug 04 '22 at 10:51
  • Constructor should be used to initialise anything you care about having an initial value. Getters/Setters are also good practice, as allows you to set/retrieve values and not care about their implementation, i.e. you have the flexibility to rename things inside you're class as it evolves while something external to that class can use a getter and not care about this. – Brian Aug 04 '22 at 10:56

0 Answers0