2012-08-24 162 views
1

我正在研究一個涉及製作電子郵件類的PHP項目。我有一個Java背景,似乎無法弄清楚調用對象方法的語法。對象的調用方法

我會縮寫代碼:

FILE 1:

class Emails { 

protected $to; 

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

public function getTo() { 
    return $to; 
} 

FILE 2:

require("../phpFunctions/EmailClass.php");//include the class file 
$email = new Emails("<email here>"); 
echo $email->getTo();//get email and return it 

然而,會過()返回保持沒有任何,或者,如果我改變返回到$ this - > $ to,我收到一個「空字段」錯誤。

請幫助我瞭解方法在這種情況下如何工作(並原諒雙關語......)。在Java中,你只需調用email.getTo()...

+1

只是一個提示前綴:函數構造非常PHP 4,你可能想使用'__construct' – Sammaye

+1

$這個 - >嘗試在地方的$這 - > $到 – amitchhajer

+1

值得閱讀:[PHP類和對象](http://php.net/manual/en/language.oop5.php) – Jocelyn

回答

2
public function __construct ($_to) { 
    $this->to = $_to; 
}  
public function getTo() { 
    return $this->to; 
} 
+0

@jeroen固定。謝謝。 –

+0

我已經注意到了,並upvoted ... – jeroen

+0

哇,非常感謝你!你不知道我在這個簡單的問題上撞了多久... – user1403777

0

用於複製和粘貼的緣故:

class Emails { 

protected $to; 

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

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

} 

使用$this範圍將得到類定義中定義的變量。

0

在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; 
}