[請益] 物件導向小問題 <已解決>
各位好 ,
我最近在練習寫物件導向,以下是書本上的範例.
我有點看不太明白,請各位高手幫忙了!
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
12/23 20:45, 1F
→
12/23 20:46, , 2F
12/23 20:46, 2F
→
12/23 22:06, , 3F
12/23 22:06, 3F
PHP 近期熱門文章
PTT數位生活區 即時熱門文章