<?php
class Add {
protected $x;
public function setX($value)
{
$this->x = $value;
}
public function setY($value)
{
$this->y = $value;
}
public function getX()
{
return $this->x;
}
public function getY()
{
return $this->y;
}
protected $y;
public function execute()
{
echo $this->x + $this->y . '<br />';
}
}
$Add = new Add();
$Add->setX(10);
$Add->setY(3);
$Add->execute();
class Add2 {
protected $x;
protected $y;
const DEFAULT_X = 10;
public function setX($value)
{
if (is_numeric($value)) {
$this->x = $value;
return $this->x;
} else {
trigger_error('setXメソッドの実行に失敗しました。',
E_USER_WARNING);
}
}
public function setY($value)
{
if (is_numeric($value)) {
$this->y = $value;
return $this->y;
} else {
echo 'setYメソッドの実行に失敗しました。';
return $this->getY();
}
}
public function getX()
{
if (!isset($this->x)) {
$this->x = self::DEFAULT_X;
}
return $this->x;
}
public function getY()
{
if (!isset($this->y)) {
$this->y = $this->getDefaultY();
}
return $this->y;
}
public function getDefaultY()
{
return 5;
}
public function execute($args = array())
{
if (isset($args['x'])) {
$x = $this->setX($args['x']);
} else {
$x = $this->getX();
}
if (isset($args['y']) OR !is_numeric($args['y'])) {
$y = $this->getY();
} else {
$y = $args['y'];
}
echo $x + $y . '<br />';
}
}
$Add = new Add2();
$Add->execute(array('x' => 10, 'y' => 10));
;
$Add->execute();
?>
まとめ
- セッタとゲッタは、カプセル化以外にも役立つ場面が多い。
- たとえば、セットするときにバリデーターとして。
- セットされていない値をゲットされたときに振る舞いを指定できる。
- たとえば、デフォルト値を返す、エラー、例外を返す・・・
- 最終的な結果を出力するとき、引数を指定する方法とプロパティに設定する方法、2種類を簡単に提供できる。