2014-12-04 72 views
1

我有這個PHP函數來添加一個對象到數據庫,但它給我一些麻煩,使其工作。我很習慣java的方式,所以我試圖遵循相同的模式,我得到一個錯誤消息,說:「嚴格的標準:只有變量應通過引用傳遞」。 這是代碼:通過引用傳遞一個對象屬性

public function saveUser(User $user){ 
    $this->connection = DaoFactory::openConnection(); 
    $this->query = $this->connection->prepare($this->SAVE_QUERY); 

    $this->query->bindParam(':name', $user->getName()); 
    $this->query->bindParam(':lastName', $user->getLastName()); 
    $this->query->bindParam(':age', $user->getAge()); 
    $this->query->bindParam('gender', $user->getGender()); 
    $this->query->bindParam(':email', $user->getEmail()); 
    $this->query->bindParam(':password', $user->getPassword()); 

    $this->query->execute(); 
    $this->connection = null; 

} 

我搜索,我發現對象屬性應放置在一個變量來避免這個問題,但這樣做,代碼變得非常混亂和complex.Example:

$name = $user->getName(); 
$this->query->bindParam(':name',$name); 

有沒有其他方法可以解決這個問題?

回答

2

bindParam需要一個通過引用傳遞的變量,而是給它一個從函數返回的值,該值不能被引用傳遞。相反,請使用其他API方法bindValue()來綁定您的值。

請參閱https://stackoverflow.com/a/14413428/476的區別是什麼。

+0

Thaks,解決了這個問題,現在代碼看起來很漂亮。 – 2014-12-04 02:51:48