Я использую 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");
}
Я прочитал несколько статей / ответов, но они были связаны со статическими функциями / переменными, поэтому я не понимаю, как это применимо.
2 ответа
В 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");
Проблема в том, как вы вызываете метод в своем тесте. Попробуйте это вместо:
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
Новые вопросы
php
PHP - это широко используемый высокоуровневый, динамический, объектно-ориентированный и интерпретируемый язык сценариев, в первую очередь предназначенный для серверной веб-разработки. Используется для вопросов о языке PHP.