2012-12-02 87 views
1

我的代碼戰鬥:

$worker = new Worker(); // :| 
$worker->addWorker; 
//testing     
//testing 
// $_SESSION['worker']->addWorker(); 
echo $_POST['name']; 
echo $worker->name; 

應該最後兩行應該表現出相同的值。類中的賦值方法如下所示:

public function addWorker() 
{ 
     $this->name = $_POST['name']; 
     $this->surname = $_POST['surname']; 
     $this->dob = $_POST['dob']; 
     $this->skills = $_POST['skills']; 
     $this->postcode = $_POST['postcode']; 
     $this->street = $_POST['street']; 
     $this->email = $_POST['email']; 
     $this->tel = $_POST['tel']; 
     $this->erefnumber = $_POST['erefnumber']; 
} 

我已經聲明瞭類Worker屬性。問題是我沒有任何錯誤,$ worker-> name只是給出了一些東西。 echo $ _POST ['name']工作正常。

+1

爲什麼不打電話給addWorker作爲函數? –

+0

你可能想考慮提煉你的Worker api。 「addWorker」意味着你將一名工人添加到另一名工人......這有意義嗎?也許更好的名字就像「setFromArray」。然後你可以傳遞$ _POST數組給它。 –

回答

4

你的代碼幾乎是好的,但你這樣做:

$worker->addWorker; 

,而應該是:

$worker->addWorker(); 

此外,爲了提高代碼的可讀性,我會考慮改變addWorker()要求數組參數:

public function addWorker(array $postArray) { 
    $this->name = $postArray['name']; 
    .... 

and pass $_POST while invoking:

$worker->addWorker($_POST);