无法将$ _POST ['variable']分配给对象属性

时间:2012-12-02 15:27:48

标签: php class object post oop

我正在与代码作斗争:

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

哪两个最后一行应显示相同的值。类中的assign方法如下所示:

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 个答案:

答案 0 :(得分:4)

您的代码几乎没问题,但您确实:

$worker->addWorker;

虽然它应该是:

$worker->addWorker();

另外,为了提高代码的可读性,我考虑将addWorker()更改为要求数组参数:

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

并在调用时传递$_POST

$worker->addWorker( $_POST );