WhoobWhoob WhoobWhoob - 8 days ago 7
PHP Question

Should I create this accessors

So I got this example layout.

private $_getMilk() = '';

public function getMilk():string {
return $this->_milk;
}

public function setMilk(string $milk) {
$this->_milk = $milk;
}


SetMilk is also used to empty milk which sounds weird to me why set empty string if you ask for milk.

Should I instead also create the function emptyMilk. (asume the milk property is getting called alot)

public function emptyMilk() {
$this->_milk = '';
}

Answer

A benefit of a seperate emptyMilk() function is that it allows you to use a special representation for an empty object, rather than exposing that to the callers.

private $is_empty = true;

public function getMilk(): string {
    if ($this->$is_empty) {
        throw new Exception("Empty milk");
    }
    return $this->$_milk;
}

public function setMilk(string $milk) {
    $this->is_empty = false;
    $this->_milk = $milk;
}

public function emptyMilk() {
    $this->is_empty = true;
    $this->_milk = null;
}

public function gotMilk(): boolean {
    return !$this->is_empty;
}

This allows you to use any value for $_milk rather than making one value special.

Comments