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 關注
- 130 瀏覽
添加回答
舉報