我喜欢使用 PDO::FETCH_CLASS 来获取对象数组,应该调用构造函数,因为我需要此类中的构造函数。作为第三个参数,我使用数据库表中的列名。结果我得到了列的名称,但不是数据库中的预期值。 我正在使用 mariaDB。
没有构造函数(并且只有 2 个参数),我得到一个包含正确对象的数组。
$dbh = Db::connect();
$sql = 'SELECT * FROM dancer';
$stmt = $dbh->prepare($sql);
$stmt->execute();
// additional "|PDO::FETCH_PROPS_LATE" in 1. argument ignores
// the constructor
$dancers = $stmt->fetchAll(PDO::FETCH_CLASS
,"Dancer"
,array("firstName","lastName","id")
);
预期结果:
[0] => Dancer Object
(
[id:Dancer:private] => 7
[firstName:Dancer:private] => Carl
[lastName:Dancer:private] => Classen
)
实际结果:
[0] => Dancer Object
(
[id:Dancer:private] => id
[firstName:Dancer:private] => firstName
[lastName:Dancer:private] => lastName
)
PHP 类
class Dancer
{
private $id;
private $firstName;
private $lastName;
public function __construct($firstName, $lastName, $id = null)
{
if (isset($id)){
$this->id = $id;
}
$this->firstName = $firstName;
$this->lastName = $lastName;
}
#GETTER AND SETTER
public static function getAll()
{
try {
$dbh = Db::connect();
$sql = 'SELECT * FROM dancer';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$dancers = $stmt->fetchAll(PDO::FETCH_CLASS
,"Dancer"
,array("firstName","lastName","id")
);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
return $dancers;
}
}
最佳答案
自从我使用 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;
}
关于php - PDO::FETCH_CLASS,构造函数参数怎么写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57821424/