php - 如何在 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 类和方法,但它不是这样工作的。
要点在这里——
- 我在同一张表中插入评论和回复。
- 我在同一页面上使用 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 而不会出现任何错误?
解决方案
推荐阅读
- arrays - 如何将对象数组作为道具传递给反应原生的自定义组件?
- c++ - 在 C++ 中实现方法的这种方式是什么?
- python - 倒数计时器未从给定值开始
- c# - 有没有办法统一找到从广告中赚到的钱
- shell - 如何仅在unix文件的第一行中搜索单词
- javascript - 如何在 Javascript 中做到这一点
- ruby-on-rails - 如何使用 Rails 中的固定装置测试 has_many :through 关联?
- python - RuntimeError("grad 只能为标量输出隐式创建")
- javascript - 在个人资料图片 Firebase Web Realtime-Database 下显示名称
- c# - 使用 C# 中的 NAudio 将 M4A 音频文件转换为 MP3 的问题/错误