<h1>Blog</h1>
<?php foreach ($this->posts as $post):?>
<article>
<h1 id="post<?= $post->getId() ?>"><?= $post->getTitle() ?></h1>
<p>
<?= $post->getText() ?>
</p>
</article>
<?php endforeach?>
这段代码如何理解?

解决方案 »

  1.   

    等於<h1>Blog</h1>
    <?php for($i=0; $i<count($this->posts); $i++):?>
    <article>
        <h1 id="post<?= $this->posts[$i]->getId() ?>"><?= $this->posts[$i]->getTitle() ?></h1>
        <p>
            <?= $this->posts[$i]->getText() ?>
        </p>
    </article>
    <?php endfor?>
    foreach其實就是把數組的每一個元素取出,
    例如foreach ($this->posts as $post)
    就是把$this->posts中的每一個元素循環賦值到$post。如果用for
    post相當於 $this->posts[$i]
      

  2.   

    <h1 id="post<?= $this->posts[$i]->getId() ?>"><?= $this->posts[$i]->getTitle() ?></h1>
    里的
    <?= $this->posts[$i]->getId() ?>
    怎么理解呢?
      

  3.   

    讲错了吧?哪来的 $this ?
      

  4.   

    $this->posts  直接等于 $posts不就是的