【问题标题】:phpunit how to solve Error: Using $this when not in object contextphpunit如何解决错误:不在对象上下文中使用$this
【发布时间】:2017-09-21 06:37:56
【问题描述】:

我正在使用 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("m.w@mail.com",["s.u@mail.com"],"phpunit testting","test true"),"send email");
    }

我已经阅读了一些文章/答案,但它们与静态函数/变量有关,所以我不明白这是如何应用的。

【问题讨论】:

  • 你正在静态调用你的方法。
  • 您在最后一个之后还缺少一个结束},还是我缺少一个?
  • 刚刚检查确定,您肯定错过了结束}
  • 大括号在那里,不知道为什么它没有复制过来
  • @Maerlyn 怎么称呼它?这对我来说没有多大意义

标签: php phpunit php-7


【解决方案1】:

在 php 中,:: 是一个标记,它允许访问类的静态、常量和重写的属性或方法。所以Notification::sendEmail()就是调用Notification类的静态方法。

当调用静态方法时,不会创建对象的实例。所以$this 在声明为静态的方法中不可用。你需要初始化一个Notification类的对象然后调用sendEmail

$this->assertTrue((new Notification())->sendEmail("m.w@mail.com",["s.u@mail.com"],"phpunit testting","test true"),"send email");

【讨论】:

    【解决方案2】:

    问题在于您如何在测试中调用该方法。试试这个:

    public function testEmail()
    {
        $notification = new Notification();
    
        $this->assertTrue($notification->sendEmail("m.w@mail.com",["s.u@mail.com"],"phpunit testting","test true"),"send email");
    }
    

    您可能还想了解 Notification:: 与 $this:https://secure.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class 的区别

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 2010-12-11
      • 1970-01-01
      • 2014-06-20
      相关资源
      最近更新 更多