有没有更好的方法来返回db结果的对象?
我知道“return $statement-> fetchall(PDO :: FETCH_CLASS,’modelClassName’);”但它只适用于fetchall功能?
class modelArea extends Model { public $areaID; public $postcode; public static function find($condition,$parameters) { $query = "SELECT * FROM area WHERE " . $condition; $statement = self::getDb()->prepare($query); if (!$statement->execute($parameters)) return false; $query = $statement->fetch(PDO::FETCH_ASSOC); $a = new modelArea(); $a->areaID = $query['areaID']; $a->postcode = $query['postcode']; return $a; } }
PDOStatement::fetchObject
方法可以满足您的需求.
您可以像以下一样使用它:
$a = $statement->fetchObject('modelArea');
这将导致$a成为类modelArea的对象,相当于您提供的代码.