01 | <?php |
02 | cmd($argc , $argv); |
03 | //コマンド |
04 | function cmd($num,$param){ |
05 | if ($num < 2){ |
06 | echo "コマンドが入力されていません。\n" ; |
07 | return ; |
08 | } |
09 | commandExec($param); |
10 | } |
11 |
12 | //コマンドの実行 |
13 | function commandExec($arg) |
14 | { |
15 | switch ($arg[1]){ |
16 | case "test" : |
17 | if ( count ($arg) < 3){ echo "引数が足りていません\n" ; return ;} |
18 | $cmd = new TestCommand($arg[2]); |
19 | break ; |
20 | default : |
21 | echo "設定されていないコマンドです。\n" ; |
22 | return ; |
23 | } |
24 | $cmd->execute(); |
25 | } |
26 |
27 | /*********************** |
28 | * |
29 | * スーパークラス |
30 | * |
31 | **********************/ |
32 | abstract class AbstractCommand{ |
33 | protected $states; |
34 | abstract public function execute(); |
35 | abstract public function toString(); |
36 | } |
37 |
38 | /*********************** |
39 | * |
40 | * 子クラス |
41 | * |
42 | ***********************/ |
43 | class TestCommand extends AbstractCommand |
44 | { |
45 | private $param; |
46 | public function TestCommand($param){ |
47 | $this->param = $param; |
48 | } |
49 |
50 | public function execute(){ |
51 | |
52 | echo $this->param . "\n" ; |
53 | } |
54 |
55 | public function toString() |
56 | { |
57 | return "TestCommand" ; |
58 | } |
59 |
60 | } |
これを実行すると。
1 | mr-elephant:php shuzo$ php cmd.php test hoge |
2 | hoge |
出力されました。上の内容でちょっとつまずいたところは、
01 | class TestCommand extends AbstractCommand |
02 | { |
03 | private $hoge; |
04 | public function TestCommand($param){ |
05 | |
06 | $hoge = $param; |
07 | } |
08 |
09 | public function execute(){ |
10 | echo $hoge . "\n" ; |
11 | } |
12 |
13 | public function toString() |
14 | { |
15 | return "TestCommand" ; |
16 | } |
17 |
18 | } |
上のやり方だと出力されず、メンバ変数へのアクセスには必ず$this->hogeを使うとのこと。省略しちゃだめってことですね。
0 件のコメント:
コメントを投稿