Is it recommended to set the function bmiberechnen() as protected for better data encapsulation in a PHP class?
To achieve better data encapsulation in a PHP class, it is recommended to set the function bmiberechnen() as protected. By making the function protected, it restricts access to the function from outside the class, ensuring that it can only be accessed by the class itself and its subclasses. This helps to maintain the integrity of the class and its data, preventing external interference.
class BMI {
private $weight;
private $height;
public function __construct($weight, $height) {
$this->weight = $weight;
$this->height = $height;
}
protected function bmiberechnen() {
return $this->weight / ($this->height * $this->height);
}
public function getBMI() {
return $this->bmiberechnen();
}
}
$bmi = new BMI(70, 1.75);
echo $bmi->getBMI(); // Output: 22.86