在使用 fetchMode PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE 循环从 PHP PDO 调用 fetchAll() 中返回的对象时,我正在尝试使用父类中定义的方法。
我设置了所有属性,但由于某种原因我无法调用这些方法 - 这就是我所拥有的:
abstract class Person {
protected $_table;
protected $Db;
public $id;
public $first_name;
public $last_name;
public $email;
private $_password;
private $_salt;
public function __construct() {
$this->Db = new MySQL();
}
public function get($id = null) {
$this->bind($this->Db->get($this->_table, $id));
}
public function save() {
// code goes here
}
}
class Client extends Person {
protected $_table = 'users';
public $address_1;
public $address_2;
public $town;
public $region;
public $country_id;
public $country_name;
public function __construct($id = null) {
parent::__construct();
$this->get($id);
}
public function getAll() {
$sql = "SELECT *
FROM `{$this->_table}`
ORDER BY `first_name` ASC";
return $this->Db->getObjects(__CLASS__, $sql);
}
}
$objClient = new Client();
$users = $objClient->getAll();
if (!empty($users)) {
foreach($users as $user) {
echo $user->first_name.' '.$user->last_name.'<br />';
$user->telephone = '11111';
$user->save();
}
}
当我运行它时,我得到:
致命错误:调用未定义的方法 stdClass::save() in...
这是 $user 的一次迭代的 var_dump() 的输出:
object(stdClass)#6 (26) {
["id"]=> string(1) "7"
["first_name"]=> string(6) "First Name"
["last_name"]=> string(4) "Last Name"
["address_1"]=> NULL
["address_2"]=> NULL
["town"]=> NULL
["region"]=> NULL
["post_code"]=> NULL
["country_id"]=> string(1) "2"
["country_name"]=> string(1) "United Kingdom"
["email"]=> string(21) "email@email.com"
["password"]=> string(100) "ff4a140e5c03ab5ssf5dce455594e485fasa5cb2cd22ce715c086"
["salt"]=> string(9) "salt8877"
}
这是 MySQL() 类的 getObjects() 方法:
public function getObjects($className = null, $sql = null, $params = null) {
if (!empty($className) && !empty($sql)) {
$params = is_array($params) ? $params : array($params);
try {
$this->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, $className);
$statement = $this->query($sql, $params);
$result = $statement->fetchAll($this->_fetch_mode);
$statement->closeCursor();
return $result;
} catch (PDOException $e) {
$this->exceptionOutput($e);
}
}
}