Php 对象上的调用方法

Php 对象上的调用方法,php,Php,我正在从事一个PHP项目,该项目涉及制作一个电子邮件类。我有Java背景,似乎无法理解在对象上调用方法的语法 我将缩写代码: 文件1: class Emails { protected $to; public function Emails ($_to) { //constructor function. $to = $_to; } public function getTo () { return $to; } 文件2: require("../phpFunctions/E

我正在从事一个PHP项目,该项目涉及制作一个电子邮件类。我有Java背景,似乎无法理解在对象上调用方法的语法

我将缩写代码:

文件1:

class Emails {

protected $to;

public function Emails ($_to) {
 //constructor function. 
  $to = $_to;
}

public function getTo () {
  return $to;
}
文件2:

require("../phpFunctions/EmailClass.php");//include the class file
$email = new Emails("<email here>");
echo $email->getTo();//get email and return it
require(“../phpFunctions/EmailClass.php”)//包括类文件
$email=新邮件(“”);
echo$email->getTo()//获取电子邮件并将其返回
但是,getTo()会一直不返回任何内容,或者,如果将返回值更改为$this->$to,则会收到一个“empty field”错误


请帮助我理解在这种情况下方法是如何工作的(请原谅双关语…)。在Java中,您只需调用email.getTo()…

即可进行复制和粘贴:

class Emails {

protected $to;

public function __construct($_to) {
 //constructor function. 
  $this->to = $_to;
}

public function getTo () {
  return $this->to;
}

}

使用
$this
作用域将获得在类定义中定义的变量。

在PHP中,变量不是实例作用域,除非前缀为
$this

public function getTo () {
  // $to is scoped to the current function
  return $to;
}

public function getTo () {
  // Get $to scoped to the current instance.
  return $this->to;
}

提示:函数构造非常适合PHP4,您可能想尝试使用
\uu构造
$this->来代替$this->$toWorth阅读:我不知道java,但总的来说php手册很棒,几乎在任何Google搜索中都是第一位的。@Sammaye感谢您的提示。这就是我习惯在Java中使用构造函数的方式:)但是我现在已经更新了我的PHP代码哇,非常感谢!你不知道我为这个简单的问题绞尽脑汁多久了。。。
public function getTo () {
  // $to is scoped to the current function
  return $to;
}

public function getTo () {
  // Get $to scoped to the current instance.
  return $this->to;
}