我是新来的,也是 PHP 新手..
只是想知道如何制作我自己的灵活循环,就像在 WordPress 中一样......
注意我不是在谈论 wordpress..我想在我自己的 PHP 应用程序上实现它...
我们回顾一下WP,有一段代码是这样的:
while (have_post() : thepost())// .. bla bla...
echo the_title();
echo the_content();
endwhile; // this is just an ilustration
你能弄清楚 have_post() 或 the_post() 如何与数据库交互吗?
这样它们就可以循环..
thanks..
WordPress 使用这些函数在循环迭代时修改的全局变量。例如。:
var $posts = null;
var $post = null;
var $post_count = 0;
var $post_index = 0;
function have_post() {
global $posts, $post_count, $post_index;
$post_index = 0;
// do a database call to retrieve the posts.
$posts = mysql_query('select * from posts where ...');
if ($posts) {
$post_count = count($posts);
return true;
} else {
$post_count = 0;
return false;
}
}
function thepost() {
global $posts, $post, $post_count, $post_index;
// make sure all the posts haven't already been looped through
if ($post_index > $post_count) {
return false;
}
// retrieve the post data for the current index
$post = $posts[$post_index];
// increment the index for the next time this method is called
$post_index++;
return $post;
}
function the_title() {
global $post;
return $post['title'];
}
function the_content() {
global $post;
return $post['content'];
}
不过,我绝对会推荐使用 OOP 风格的编码,而不是 WordPress 的编码方式。这将保留在对象实例内定义的变量,而不是全局可访问的。例如。:
class Post {
function __construct($title, $content) {
$this->title = $title;
$this->content = $content;
}
function getTitle() {
return $title;
}
function getContent() {
return $content;
}
}
class Posts {
var $postCount = 0;
var $posts = null;
function __construct($conditions) {
$rs = mysql_query('select * from posts where $conditions...');
if ($rs) {
$this->postCount = count($rs);
$this->posts = array();
foreach ($rs as $row) {
$this->posts[] = new Post($row['title'], $row['content']);
}
}
}
function getPostCount() {
return $this->postCount;
}
function getPost($index) {
return $this->posts[$index];
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)