[請益] 物件導向小問題 <已解決>

看板PHP作者 (阿雁 < 小弟 ~*)時間17年前 (2008/12/23 19:19), 編輯推噓0(003)
留言3則, 2人參與, 最新討論串1/1
各位好 , 我最近在練習寫物件導向,以下是書本上的範例. 我有點看不太明白,請各位高手幫忙了! PHP-Class Message部份 private $count; private $entries; public function __construct() { $this->count = 0; } public function add($name,$msg) { $this->entries[$this->count++] = array('name'=>$name, 'msg' =>$msg); } public function got($index) { if($index >= 0 && $index<$this->count) return $this->entries[$index]; else return NULL; } public function howmany() { return $this->count; } PHP呼叫物件部份 $obj = new Message; $obj->add('Hunter','第一筆'); $obj->add('Amy','這是第二筆') HTML部份 <body> <?php $total = $obj->howmany(); echo "共 $total 筆"; ?> <p> <?php for($i=0;$i < $total;$i++) { $entry = $obj->got($i); echo "<p>留言人:{$entry['name']} <p>內容:{$entry['msg']}<p>"; } ?> </body> 其中add方法的$this->entries陣列 , 起始值是 $this->count++ , 所以就是 1 了? 在後來的印出中(迴圈) , got方法的輸入值是從 0 開始跑 , 那麼entries[0]不就是空的 ? 而$total = $this->count最後的值就是 2 , 那在got方法中 應該是 0 -> 1 -> 結束 , 照這樣來說應該會輸出錯誤才會阿 , 為甚麼最後會是完完整整成功輸出 0.0 ? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.110.82.96 ※ 編輯: kusoayan 來自: 123.110.82.96 (12/23 19:20)

12/23 20:45, , 1F
add()中的$this->count++是先取用完count的值完再+1
12/23 20:45, 1F

12/23 20:46, , 2F
可以看成是先完成entries[count]=... 再作count++
12/23 20:46, 2F

12/23 22:06, , 3F
瞭解了 :D 謝謝你!
12/23 22:06, 3F
文章代碼(AID): #19KCakBe (PHP)
文章代碼(AID): #19KCakBe (PHP)