如何检查方法是否返回true?用户状态判断方法的循环应用咨询
Hi there! Let's break down your two questions clearly and practically:
Checking if a method returns true is straightforward—you can use it directly in a conditional statement. Since your isClosed() method returns a boolean, here are two common approaches:
- Basic truthy check (works because
truecounts as a "truthy" value in PHP):if ($yourUserInstance->isClosed()) { // Run code when the method returns true } - Strict equality check (safer if you want to ensure it’s exactly
true, not another truthy value like1):if ($yourUserInstance->isClosed() === true) { // Run code only when the method returns the exact boolean true }
user_closed is "yes" First, let’s fix up your isClosed() method—it has a small bug and a critical security risk (SQL injection from directly inserting $username into the query). Here’s an improved, safer version:
public function isClosed() { $username = $this->user['username']; // Use prepared statements to block SQL injection (this is non-negotiable for security!) $stmt = mysqli_prepare($this->connection, "SELECT user_closed FROM users WHERE username = ?"); mysqli_stmt_bind_param($stmt, "s", $username); // "s" tells MySQL we're passing a string mysqli_stmt_execute($stmt); mysqli_stmt_bind_result($stmt, $userClosed); mysqli_stmt_fetch($stmt); mysqli_stmt_close($stmt); // Simplify logic: directly return whether user_closed equals "yes" return $userClosed === "yes"; }
Now, for your post loading loop: you can check the user’s closed status inside the loop and use break to stop the loop immediately when you hit a closed user. Here’s how that might look in practice:
// Assume you have a query fetching your posts $postQuery = mysqli_query($this->connection, "SELECT * FROM posts ORDER BY created_at DESC"); while ($post = mysqli_fetch_array($postQuery)) { // Get the user associated with this post (adjust this to match your code structure) $postAuthor = new User($post['username']); // Replace with your actual user class setup // If the author is closed, terminate the loop right away if ($postAuthor->isClosed()) { break; } // If we reach here, the author is active—display the post echo "<div class='post'> <h4>" . htmlspecialchars($post['title']) . "</h4> <p>" . htmlspecialchars($post['content']) . "</p> </div>"; }
Bonus Performance Tip
Instead of checking in the loop, you could filter out posts from closed users directly in your SQL query. This is more efficient because it reduces the amount of data you fetch from the database:
SELECT posts.* FROM posts JOIN users ON posts.username = users.username WHERE users.user_closed != 'yes' ORDER BY posts.created_at DESC
This way, your loop will only process posts from active users, and you won’t need to call isClosed() at all!
内容的提问来源于stack exchange,提问作者Alexandre Allegro

