Use accessor methods to assign property values

Aug 24, 2020 PHP

Put a value in a class property

If you create an instance with a class and put a value in a property *** Instance -> property name = value; can be implemented by ***.

class CalBMI {

  public $_weight; // weight (kg)
  public $_height; // height (m)

  public function __construct($weight,$height){
      $this->_weight = $weight;
      $this->_height = $height;
  }

  public function getBMI(){
      return $this->_weight / ($this->_height * $this->_height);
  }

}
require_once'CalBMI.php';

$calBMI = new CalBMI(60,1.6);
echo $calBMI->getBMI(); //23.4375

However, users don’t always work as expected. So sometimes I put a letter where I put a number

require_once'CalBMI.php';

$calBMI = new CalBMI(60,'height');
echo $calBMI->getBMI(); // Warning: A non-numeric value encountered

To prevent such scandals, the properties of the class are basically private and cannot be directly accessed by the user. Access using *** accessor method ***.

class CalBMI {

  private $_weight; // weight (kg)
  private $_height; // height (m)

  public function __construct($weight,$height){
      $this->setWeight($weight);
      $this->setHeight($height);
  }

  public function setWeight($weight){
      $this->_weight = is_numeric($weight)? $weight :60; // If anything other than numbers is entered, set 60 to weight with Default
  }

  public function setHeight($height){
      $this->_height = is_numeric($height)? $height :1.6; // If anything other than numbers enters, set 1.6 as height with Default
  }

  public function getWeight(){
      return $this->_weight;
  }

  public function getHeight(){
      return $this->_height;
  }

  public function getBMI(){
      return $this->getWeight() / ($this->getHeight() * $this->getHeight());
  }

}
require_once'CalBMI.php';

$calBMI = new CalBMI(60,'height');
echo $calBMI->getBMI(); // 23.4375

#Reference Self-study PHP 3rd Edition