Search code examples
phpclassprivatesetter

How to set class variables in PHP?


I have a class in php and want to know if there is a specific convention how to set these private variables in my constructor.

Should I set them with my setter or with this?

class foo {

  private $bar;

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

  public function setBar($bar) {
    $this->bar = $bar;
  }

  public function getBar() {
    return $this->bar;
  }
}

OR

class foo {

  private $bar;

  public function __construct($foobar) {
     $this->setBar($foobar);
  }

  public function setBar($bar) {
    $this->bar = $bar;
  }

  public function getBar() {
    return $this->bar;
  }
}

Or is my question just philosophical? Same question could be asked with getters. But I guess you have to use setters and getters when handling private variables of your parent class.


Solution

  • You should use the setBar in the constructor because of data validation, and future maintenance.

    // a developer introduces a bug because the string has padding.
    $foo->setBar("chickens   ");
    
    // the developer fixes the bug by updating the setBar setter
    public function setBar($bar) {
        $this->bar = trim($bar);
    }
    
    // the developer doesn't see this far away code
    $f = new foo("chickens   ");
    

    The developer sends the code to production thinking he fixed the bug.