0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Getter、Setterがある時とない時の違いとは?

Last updated at Posted at 2023-03-11

1.Getter、Setterがない場合
クラス内の変数を直接クラスの外から操作可能です。

<?php
class Weather{
    public $currentWeather;
}

$weather = new Weather();
//Weatherクラスの変数をクラスの外から操作している
$weather->currentWeather = "晴れ";
echo $weather->currentWeather;
?>

2.Getter、Setterがある場合
クラス内の変数をクラスの外から操作できないようにしています。その代わりに、クラス外から間接的に変数を操作するために、ゲッターとセッターのメソッドを用意しています。

<?php
class Weather
{
  //修飾子をprivateにすることで、クラス外から変数をいじれなくなっている
  private $currentWeather;

  //変数$currentWeatherをクラス外から間接的にいじれるようにするために、
  //以下2つのメソッドを用意する

  //ゲッター
  public function getCurrentWeather()
  {
      return $this->currentWeather;
  }
  
  //セッター 
  public function setCurrentWeather($currentWeather)
  {
      $this->currentWeather = $currentWeather;
  }
 
}

$weather = new Weather();
//変数$currentWeatherをクラス外から操作できない
//そのためセッターメソッドを用いて変数$currentWeatherを操作する
$weather->setCurrentWeather('晴れ');
//上記で操作した$currentWeatherを出力する
echo $weather->getCurrentWeather();
?>

3、まとめ
ゲッター、セッターがあるということは、外部からクラス内の変数を直接操作させない代わりに、外部から変数を操作できるメソッドがあるということでした。

参照
https://qiita.com/kanohisa/items/154e70ed82af2347ddb2
https://wa3.i-3-i.info/word15856.html

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?