【问题标题】:Pass an object attribute by reference通过引用传递对象属性
【发布时间】:2014-12-04 02:33:58
【问题描述】:

我有这个 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;

}

我已经搜索过,我发现应该将对象属性放在一个变量中以避免这个问题,但是这样做,代码变得非常混乱和复杂。示例:

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

有没有其他方法可以解决这个问题?

【问题讨论】:

    标签: php error-handling


    【解决方案1】:

    bindParam 需要一个通过引用传递的变量,而是给它一个从函数返回的值,该值不能通过引用传递。因此,请改用其他 API 方法 bindValue() 来绑定您的值。

    请参阅https://stackoverflow.com/a/14413428/476 了解区别。

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 2011-01-23
      • 1970-01-01
      • 2017-09-11
      • 2018-07-09
      • 2011-07-06
      • 2012-07-07
      • 2012-01-05
      相关资源
      最近更新 更多