【问题标题】:PHP: member functions can't access member variablesPHP:成员函数无法访问成员变量
【发布时间】: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-&gt;propertyName,而不是$this-&gt;$propertyName。放弃那些美元符号。

标签: php class


【解决方案1】:

那是因为你在做$this-&gt;$subject,你的意思是$this-&gt;subject

更完整的答案:

PHP 允许您拥有自定义变量名称。例如。你可以设置

$i = 0;

$var$i = "abc";

那么$var0 将包含“abc”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2018-06-04
    • 1970-01-01
    • 2023-03-23
    • 2021-02-04
    • 2014-07-29
    相关资源
    最近更新 更多