我一直在努力学习编写更多OO并且一直在使用PDO。但是,我很难在文档中找到几个PDO函数的例子。
我正在使用PDO的fetch_class函数,以下代码根据display()函数成功回显了每个团队的信息。我的问题是四重的;
1)每次使用PDO fetch_class时是否都会创建TeamInfo类的新实例?
2)如果是这样 - 每个人的名字是什么?或者它们都是作为TeamInfo创建的?
3)有没有办法在将来的代码中引用该类的特定实例?喜欢使用数组的索引值吗?
4)有没有办法为数据的每个新实例声明一个名称,因为数据是从数据库中提取的 - 可能每次都使用特定行的值(例如team_name。
代码......
class TeamInfo {
public $team_name;
public $aka;
public $website;
public $main_contact;
public $phone;
public $email;
public $other;
public function display() {
$output='';
$output.=$this->team_name;
$output.='<br>' . $this->aka;
$output.='<br>' . $this->website;
$output.='<br>' . $this->main_contact;
$output.='<br>' . $this->phone;
$output.='<br>' . $this->email;
$output.='<br>' . $this->other;
return $output;
}
}
require_once "old_pdo_enl_connect.php";
$database=dbNB_connect();
$query=$database->query("SELECT team_name, aka, website, main_contact, phone, email, other from team_directory");
foreach ($query->fetchAll (PDO::FETCH_CLASS, 'TeamInfo') as $team) {
echo $team->display() . "<hr>";
}
答案 0 :(得分:1)
1)是的。
2)将对象分配给$team
(每次迭代时被下一个对象覆盖)变量,类为TeamInfo
3)您可以保存对象数组:
$rows = $query->fetchAll(PDO::FETCH_CLASS, 'TeamInfo');
访问每一行:
$rows[0]->team_name;
4)您可以使用team_name
创建关联数组作为键:
$rows = array()
foreach($query->fetchAll(PDO::FETCH_CLASS, 'TeamInfo') as $row) {
$rows[$row->team_name] = $row;
}
echo $rows['ExampleTeam']->website;