简体   繁体   中英

Method as Condition in While Loop

Need to create a Method like WordPress's function have_posts() for templating.

Method goes something like this:

class posts{
    public function have_posts(){
        $query = 'SELECT * FROM posts';
        $result = mysql_query($query);
        return mysql_fetch_array($result);
    }
}

Using the class in the template (theme):

$posts = new posts;
while($row = $posts->have_posts()){
    echo $row['post_title'];
}

But I am trying to achieve something like:

<?php while(have_posts()){ ?>
<h1><?php post_title(); ?></h1>
<?php } ?>

Alternatives & Suggestions are also welcomed :)

For your specific question, the following should work

class posts
{
    private $_result;
    private $_current;

    public function __construct()
    {
        $query = 'SELECT * FROM posts';
        $this->_result = mysql_query($query);
    }

    public function have_posts()
    {
        return ($this->_current = mysql_fetch_array($this->_result));
    }

    public function post_title()
    {
        echo $this->_current['title'];
    }
} 

<?php $posts = new posts(); ?>

<?php while($posts->have_posts()){ ?>
    <h1><?php $posts->post_title(); ?></h1>
<?php } ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM