【发布时间】:2021-03-27 00:36:34
【问题描述】:
我正在试验 PHP 类,并创建了这个简单的类:
<?php
/* email.php
Returns a wrapper object that handles the sending of an email
*/
class Email
{
private $message = "";
private $subject = "";
private $to = "";
public function setMessage(string $newMessage) {
$this->$message = $newMessage;
}
public function setSubject(string $newSubject) {
$this->$subject = $newSubject;
}
public function setRecipient(string $newRecipient) {
$this->$to = $newRecipient;
}
public function send() {
mail($this->$to, $this->$subject, $this->$message);
}
}
$email = new Email();
$email->setRecipient('test@gmail.com');
$email->setSubject('A message');
$email->setMessage('Does this work?');
$email->send();
?>
但是,当我运行此脚本时(我通过前端的 fetch 请求调用此脚本),我收到以下错误:
Notice: Undefined variable: to in /home/jack/Projects/test/php/email.php on line 24
Notice: Undefined variable: subject in /home/jack/Projects/test/php/email.php on line 20
Notice: Undefined variable: message in /home/jack/Projects/test/php/email.php on line 16
Notice: Undefined variable: to in /home/jack/Projects/test/php/email.php on line 28
Notice: Undefined variable: subject in /home/jack/Projects/test/php/email.php on line 28
Notice: Undefined variable: message in /home/jack/Projects/test/php/email.php on line 28
我在这里做错了什么?
【问题讨论】:
-
访问属性的正确语法是
$this->propertyName,而不是$this->$propertyName。放弃那些美元符号。