LoginSignup
1
1

More than 3 years have passed since last update.

プロパティの値の代入はアクセサメソッドを使う

Posted at

クラスのプロパティに値を入れる

クラスでインスタンスを作り、プロパティに値を入れる場合は
インスタンス->プロパティ名 = 値;で実装可能。

CalBMI.php
class CalBMI {

  public $_weight; // 体重(kg)
  public $_height; // 身長(m)

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

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

}
accessor1.php
require_once 'CalBMI.php';

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

しかし、ユーザーはいつも自分が想定した通りには動いてくれない。
なので、数字を入れるところに文字を入れる場合もある

accessor1.php
require_once 'CalBMI.php';

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

このような不祥事を防ぐため、クラスのプロパティは基本privateでユーザーが直接アクセスできないようにし、
アクセサメソッドを使ってアクセスさせる.

CalBMI.php
class CalBMI {

  private $_weight; // 体重(kg)
  private $_height; // 身長(m)

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

  public function setWeight($weight){
      $this->_weight = is_numeric($weight) ? $weight : 60; // 数字以外のものが入るとDefaultで60を体重に設定
  }

  public function setHeight($height){
      $this->_height = is_numeric($height) ? $height : 1.6; // 数字以外のものが入るとDefaultで1.6を身長に設定
  }

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

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

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

}
accessor2.php
require_once 'CalBMI.php';

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

参考

独習PHP第3版

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1