PHP - 如何解决消息通知错误"不在对象上下文中使用$this"?



您好,我在 PHP PDO 中发送消息通知时遇到问题,并且 下面是我的代码 addMention sendNotification 如果有人在帖子中提到用户。

public function addMention($status,$user_id, $tweet_id){
preg_match_all("/@+([a-zA-Z0-9_]+)/i", $status, $matches);
if($matches){
$result = array_values($matches[1]);
}
$sql = "SELECT * FROM users WHERE username = :mention";
foreach ($result as $trend) {
if($stmt = $this->pdo->prepare($sql)){
$stmt->execute(array(':mention' => $trend));
$data = $stmt->fetch(PDO::FETCH_OBJ);
}
}
if($data->user_id != $user_id){
Message::sendNotification($data->user_id, $user_id, $tweet_id, 'mention');
}
}

下面是我的发送通知功能

public function sendNotification($get_id, $user_id, $target, $type){
$this->create('notification', array('notificationFor' => $get_id, 'notificationFrom' => $user_id, 'target' => $target, 'type' => $type, 'time' => date('Y-m-d H:i:s')));

$this在实例化的类对象之外不存在,则在代码示例中显示function,但没有显示周围的类。一定是你从对象上下文外部调用它。

?php
class Notification extends SomeClassWithACreateMethod
{
public function sendNotification($get_id, $user_id, $target, $type){
$this->create('notification', array('notificationFor' => $get_id, 
'notificationFrom' => $user_id, 'target' => $target, 'type' => $type, 'time' => date('Y-m-d H:i:s')));
}

尝试更多类似的东西...请记住,您调用的->create()方法也需要是此Notification类的一部分。

您需要创建一个Message对象,以便可以调用其sendNotification方法。

$msg = new Message()
$msg->sendNotification($data->user_id, $user_id, $tweet_id, 'mention');

您调用它的方式仅适用于静态方法,它不能使用$this

最新更新