我正在进行一个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
然而,getTo()保持不返回任何值,或者,如果我将返回值更改为$this->$to,我会收到一个"空字段"错误。
请帮助我理解方法在这个例子中是如何工作的(请原谅双关语…)。在Java中,你只需要调用email.getTo()…
public function __construct ($_to) {
$this->to = $_to;
}
public function getTo () {
return $this->to;
}
为了复制和粘贴:
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;
}