如果我想从数据库中获取客户的电子邮件地址,则以下内容很糟糕,因为 $row 将为表中的每个字段包含一个元素customer
:
$result = mysqli_query ('SELECT * FROM customer WHERE custid = 1');
$row = mysqli_fetch_array ($result, MYSQLI_ASSOC);
这被认为更好,因为 $row 将包含电子邮件地址的单个元素,这就是我们所需要的:
$result = mysqli_query ('SELECT email FROM customer WHERE custid = 1');
$row = mysqli_fetch_array ($result, MYSQLI_ASSOC);
我正在尝试将相同的逻辑应用于对象。如果“客户”对象有 50 个属性/字段,那么当您只需要访问一个时填充所有 50 个属性是否很常见?
下面是一个客户类和对象的基本示例,如果我们想要做的只是获取客户的电子邮件地址,而不是他们的所有其他详细信息(在此示例中,“客户”对象有 5 个属性,但实际上有可能更多):
class Customer {
private $custid;
private $firstname;
private $lastname;
private $email;
private $dateadded;
public function getCustomer ($id) {
$result = mysql_queryi ('SELECT * FROM customer WHERE custid = ' . $id);
$row = mysqli_fetch_array ($result, MYSQLI_ASSOC);
foreach ($row as $key => $value) {
if (isset ($this->$key)) {
$this->$key = $value;
}
}
}
}
$customer = new Customer ();
$customer->getCustomer (1); // All I wanted is the email address, but now I have everything :-(