简体   繁体   English

方法作为While循环中的条件

[英]Method as Condition in While Loop

Need to create a Method like WordPress's function have_posts() for templating. 需要创建类似于WordPress函数have_posts()进行模板化。

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 } ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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