2017-04-24 100 views
1

我正在使用php-7,並在運行測試時遇到此錯誤。

Error: Using $this when not in object context 

src/Notification.php:28 
tests/NotificationTest.php:10 

它未能對$this->log->info(" Message sent ");

內容

<?php 
declare(strict_types=1); 
namespace CCP; 

use CCP\MyMailer; 

class Notification{ 

    private $log; 

    public function __construct(){ 
     $this->log = $_SESSION['CFG']->log; 
    } 

    public function sendEmail(string $from, array $to, string $subject, string $body): boolean{ 
     $mail = new MyMailer; 
     $mail->setFrom($from); 
     foreach($to as $value){ 
     $mail->addAddress($value); 
     } 
     $mail->Subject = $subject; 
     $mail->Body = $body; 

     if(!$mail->send()) { 
     $this->log->error(" Message could not be sent for "); 
     $this->log->error(" Mailer error: ".$mail->ErrorInfo); 
     return false; 
     } else { 
     $this->log->info(" Message sent "); 
     } 

     return true; 
    } 
} 
?> 

我的測試

public function testEmail(){ 
     $this->assertTrue(Notification::sendEmail("[email protected]",["[email protected]"],"phpunit testting","test true"),"send email"); 
    } 

我讀了幾篇文章/答案,但他們在相互關聯的靜態函數/變量所以我不明白這是如何適用的。

+2

你靜態調用你的方法。 – Maerlyn

+0

你還錯過了最後一個關閉''',或者我錯過了? –

+0

剛剛檢查確定,你肯定**錯過了一個關閉'}'。 –

回答

2

在PHP中,::是一個令牌,它允許訪問靜態的,恆定的,並覆蓋類的屬性或方法。因此Notification::sendEmail()是爲Notification類調​​用靜態方法。

當調用靜態方法時,不會創建該對象的任何實例。因此$this在聲明爲靜態的方法內不可用。你需要初始化Notification類的對象,然後調用sendEmail

$this->assertTrue((new Notification())->sendEmail("[email protected]",["[email protected]"],"phpunit testting","test true"),"send email"); 
相關問題