2017-10-09 119 views
1

我想弄明白,我如何可以在另一個類的類中使用公共方法。我得到這個錯誤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 

我應該怎麼辦?

+1

你不能在靜態方法 – Thielicious

+0

由於您使用OOP原理用'$ this',不使用全局關鍵字。這是不好的做法 – Akintunde007

+0

比方說,我刪除了靜態關鍵字,那麼我如何才能訪問類中的方法? – dinho

回答

0

使sendNotification成爲非靜態函數。刪除static關鍵字

當方法不依賴於實例化的類時使用靜態方法。因此,爲什麼$this不能使用

在後續功能的原因,而是執行此

$message = new Message($this->pdo);//pass database connection 
$message->sendNotification();//pass the variables 
0

您正嘗試此方法訪問$這從一個靜態方法:

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的非靜態,​​並創建消息的一個實例,這樣你就可以訪問用戶的公共成員

+0

如何?,我不想包括在一個類中的文件。 – dinho

+0

$ message = new Message(); $ message-> sendNotification(...); 如果該類已經包含,它將工作。 你也可以看看psr-4自動加載,以使它更容易 – tete0148

+0

,你可以看到,在我的config.php文件中,我在類中傳遞了$ pdo變量。如果我實例化類,它會拋出錯誤。 – dinho