我想弄明白,我如何可以在另一個類的類中使用公共方法。我得到這個錯誤PHP PDO調用公共方法從其他類的不同類
Fatal error: Uncaught Error: Using $this when not in object context
我有主類用戶,其中包含插入方法,基本上這種方法插入值到數據庫。
<?php
class User{
protected $pdo;
public function __construct($pdo){
$this->pdo = $pdo;
}
public function insert($table, $fields){
//here we insert the values into database
}
}
?>
這裏是我的config.php文件實例化類,所以我可以用它們
<?php
session_start();
include 'database/connection.php';
include 'classes/user.php';
include 'classes/follow.php';
include 'classes/message.php';
global $pdo;
$userObj = new User($pdo);
$followObj = new Follow($pdo);
$messageObj = new Message($pdo);
?>
,我有其他類的消息,並遵循。在後續類我可以訪問用戶類的所有方法,並在消息類我試圖使用插入方法,它在用戶類
<?php
class Message extends User{
public function __construct($pdo){
$this->pdo = $pdo;
}
public static function sendNotification($user_id, $followerID, $type){
//calling this method from user class
$this->insert('notifications', array('By' => $user_id, 'To' => $followerID, 'type' => $type));
}
}
?>
在後續類我想要使用sendNotification的方法,記住這個方法在郵件類,並使用它的方法,從用戶類
<?php
class Follow extends User{
public function __construct($pdo){
$this->pdo = $pdo;
}
public function follow($user_id, $followerID){
//here will be query to insert follow in database
//now i need to sendNotification method from user
Message::sendNotification($user_id, $followerID, 'follow');
}
}
?>
獲取致命錯誤
Fatal error: Uncaught Error: Using $this when not in object context
我應該怎麼辦?
你不能在靜態方法 – Thielicious
由於您使用OOP原理用'$ this',不使用全局關鍵字。這是不好的做法 – Akintunde007
比方說,我刪除了靜態關鍵字,那麼我如何才能訪問類中的方法? – dinho