首页 > 解决方案 > 如何在 PHP 中为 OOPS 构建结构函数?

问题描述

我正在使用树概念在 PHP 中创建评论和回复系统。
我在我的数据库中创建了一个评论表 -

CREATE TABLE `comments` (
  `cm_id` int(11) NOT NULL,
  `cm_message` text NOT NULL,
  `postid` int(11) DEFAULT NULL,
  `user_id` int(11) NOT NULL,
  `created` datetime NOT NULL,
  `parentid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

如您所见,我已经包含了父 ID 和评论 ID 以及帖子 ID。

我的树函数

function fetchCategoryTree($parentid = 0,$user_tree_array = '') {
global $db; 
global $postid;
  if (!is_array($user_tree_array))
    $user_tree_array = array();
$stmt = $db->prepare('SELECT
    comments.cm_message, comments.cm_id,comments.parentid,comments.created,users.username, users.image 
FROM comments 
    INNER JOIN users  ON comments.user_id = users.user_id 
    WHERE comments.postid=:postid AND parentid =:parentid   ORDER by comments.cm_id DESC');  

$stmt->execute(array('parentid' => $parentid, 
                   'postid' => $postid

                ));

  if($stmt->rowCount() > 0) {
    while ($row = $stmt->fetchObject()) {
      $user_tree_array[] = array("cm_id" => $row->cm_id,"image" => $row->image,"parentid" => $row->parentid,"username" => $row->username,"created" => $row->created, "cm_message" =>$row->cm_message);
      $user_tree_array = fetchCategoryTree($row->cm_id, $user_tree_array);
    }
  }
  return $user_tree_array;
}

调用函数

$categoryList = fetchCategoryTree(); 

它正在工作,但是,正如你所看到的,我在函数中创建了一个全局 postid。如果我给里面的 postid

 $categoryList = fetchCategoryTree($postid);

并改变功能看起来像 -

function fetchCategoryTree($postid) {
    global $db; 
$parentid = 0; 
$user_tree_array = ''; 

} 

然后它不起作用。

我想将它转换为 OOPS 类和方法,但它不是这样工作的。

要点在这里——

  1. 我在同一张表中插入评论和回复。
  2. 我在同一页面上使用 while 循环通过 postid 获取评论和回复 -

喜欢 -

post 1  
comments for post 1 
with reply 


post 2 
comments for post 2 
with reply 


post n 
comments for n post  
with reply n 

在 OOPS 中做到这一点的最佳方法是什么?

类和方法

如何在调用时使用 postid 而不会出现任何错误?

标签: phppdo

解决方案


推荐阅读