以前に作成した SimpleNotepad クラスを修正します。
typeメソッドを修正する
SimpleNotepad クラスの仕様は以下のとおりです。
| プロパティ | 意味 |
|---|---|
$input_string |
入力された文字列 |
| メソッド | 処理内容 |
|---|---|
type |
$string 引数で受け取った文字列データを $input_string プロパティに追加するただし $input_string プロパティに文字列データが存在する場合は " " 半角スペースを付けてから追加する入力チェック: $string 引数が "" 空文字の場合は NotepadException (メッセージ: argument is empty.)をスローする |
show |
$input_string プロパティの内容を出力する |
get_input_string_length |
$input_string プロパティの文字列の長さを取得する |
get_word_count |
$input_string プロパティに含まれる単語の数を取得する |
reset |
$input_string プロパティを "" 空文字で初期化する |
| コンストラクタ | 処理内容 |
|---|---|
__construct |
$input_string プロパティを "" 空文字で初期化する |
typeメソッドでスローする例外をExceptionクラスからNotepadExceptionクラスに変更します。
ここではあらたに Exception クラスを継承した NotepadException クラスを作成します。
NotepadExceptionクラスにプロパティやメソッド、コンストラクタの定義はありません。
問題 7
次のプログラム( notepad_runner7.php )があります。
notepad_runner7.php
<?php
require_once("SimpleNotepad.php");
require_once("NotepadException.php");
try {
$notepad = new SimpleNotepad();
$notepad->type("one");
$notepad->type(""); # => throw Exception
$notepad->type("three");
$notepad->show();
} catch (NotepadException $e) {
echo $e->getMessage() . PHP_EOL;
}
NotepadExceptionをキャッチします。
次の実行結果のとおり動作するプログラム( SimpleNotepad.php 、 NotepadException.php )を作成してください。
実行結果
$ php notepad_runner7.php
argument is empty.
NotepadException.php
# TODO define NotepadException class.
Exceptionクラスを継承したNotepadExceptionクラスを定義します。
SimpleNotepad.php
<?php
require_once("NotepadException.php");
class SimpleNotepad
{
protected $input_string;
public function __construct()
{
$this->input_string = "";
}
public function type($string)
{
# TODO
if ($this->input_string) {
$this->input_string .= " ";
}
$this->input_string .= $string;
}
public function show()
{
echo $this->input_string . PHP_EOL;
}
public function get_input_string_length()
{
return mb_strlen($this->input_string);
}
public function get_word_count()
{
return count(explode(" ", $this->input_string));
}
public function reset()
{
$this->input_string = "";
}
}
typeメソッドを実装してください。