1 回答
TA贡献1851条经验 获得超4个赞
我已经有很长一段时间没有使用了,所以我FETCH_CLASS花了一段时间才记住它应该如何(?)挂在一起。我敲了一个测试:
class foo{
private $username;
private $userid;
public function __construct( $arg1, $arg2 ){
/* assign "ctor_args" as named properties */
$this->username=$this->$arg1;
$this->userid=$this->$arg2;
/* do something with the newly created properties */
$this->render( $arg1, $arg2 );
}
private function render( $arg1, $arg2 ){
printf('
<pre>
username: %s
userid: %s
</pre>',
$this->username,
$this->userid
);
}
}
$ctor_args=array( 'name', 'uid' );
/*
use aliases to modify column names to
indicate the assignment within the class
later
*/
$sql='select `username` as `name`, `userid` as `uid` from users';
$stmt=$db->prepare( $sql );
$res=$stmt->execute();
/* fetch results - calling the `foo` class with additional `ctor_args` */
$stmt->fetchAll( PDO::FETCH_CLASS, 'foo', $ctor_args );
这个的输出(表中只有 2 行)
username: RamRaider
userid: d6ba0682d75eb986237fb6b594f8a31f
username: Dustybin
userid: FHsdf44dfsdfcvhbfgh86237fb6b594f8a31f
因此,也许如果您将构造函数方法更改为
public function __construct($firstName, $lastName, $id = null){
if( isset( $this->$id ) ){
$this->id = $this->$id;
}
$this->firstName = $this->$firstName;
$this->lastName = $this->$lastName;
}
- 1 回答
- 0 关注
- 177 浏览
添加回答
举报
