PDO fetchObject不适用于某些私有字段

时间:2018-02-23 14:54:33

标签: php pdo

我正在努力使用PDO fetchObject。

我有供应商类:

class Supplier {

private $id;
private $companyName;
private $vatNumber;
private $address;
private $phoneNumber;
private $email;
private $responsible;

/**
 * @return mixed
 */
public function getAddress()
{
    return $this->address;
}

/**
 * @param mixed $address
 */
public function setAddress($address)
{
    $this->address = $address;
}

/**
 * @return mixed
 */
public function getCompanyName()
{
    return $this->companyName;
}

/**
 * @param mixed $companyName
 */
public function setCompanyName($companyName)
{
    $this->companyName = $companyName;
}

/**
 * @return mixed
 */
public function getId()
{
    return $this->id;
}

/**
 * @param mixed $id
 */
public function setId($id)
{
    $this->id = $id;
}

/**
 * @return mixed
 */
public function getResponsible()
{
    return $this->responsible;
}

/**
 * @param mixed $responsible
 */
public function setResponsible($responsible)
{
    $this->responsible = $responsible;
}

/**
 * @return mixed
 */
public function getVatNumber()
{
    return $this->vatNumber;
}

/**
 * @param mixed $vatNumber
 */
public function setVatNumber($vatNumber)
{
    $this->vatNumber = $vatNumber;
}

/**
 * @return mixed
 */
public function getEmail()
{
    return $this->email;
}

/**
 * @param mixed $email
 */
public function setEmail($email)
{
    $this->email = $email;
}

/**
 * @return mixed
 */
public function getPhoneNumber()
{
    return $this->phoneNumber;
}

/**
 * @param mixed $phoneNumber
 */
public function setPhoneNumber($phoneNumber)
{
    $this->phoneNumber = $phoneNumber;
}
} 

然后我在SupplierDAO中调用getById:

public function getById($id) {

    $query = "SELECT * FROM supplier where id = ?";
    $stmt = $this->dbh->prepare($query);

    if ($stmt->execute(array($id))) {
        $supplier = $stmt->fetchObject('Supplier');
    }

    $stmt = null;
    $dbh = null;

    return $supplier;

}

当我从getById(在json中)管理返回的值时,我看到:

{"error":"",
"status":"",
"supplier":{
    "company_name":"XXXX",
    "vat_number":"111111",
    "phone_number":"069341527",
    "created":"2018-02-23 14:33:09",
    "updated":"2018-02-23 14:33:09"
 }
}

为什么我看不到地址字段,电子邮件字段和负责字段?

我在某篇文章中看到,解决方案是改变字段的可见性,从私有到公共(实际上它可以工作),但我不喜欢它。

你有一些提示给我,或者我错了什么?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果要指定要包含在json_encode中的字段,可以尝试JsonSerializable