2014-12-04 73 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