相反然后使用PHP的标准类来检索值,可以使用实体类,如下所示。
Class customer {
protected $_email;
public function __construct(array $config = array()){
$this->setOptions($config);
}
public function getEmail(){
return $this->_email;
}
public function setEmail($email){
$this->_email = $email;
}
public function setOptions(array $options)
{
$_classMethods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $_classMethods)) {
$this->$method($value);
} else {
throw new Exception('Invalid method name');
}
}
return $this;
}
public function setOption($key, $value){
return $this->setOptions(array($key, $value));
}
}
现在你可以简单地做到这一点。
$W = $stmt->fetch(PDO::FETCH_ASSOC);
$customer = new Customer($w);
现在访问属性将返回null或在实体类中设置的默认值。即使它在查询结果中未定义。
$customer->getEmail();
这实际上是我正在做的事情,但如果该字段为空,并且属性未定义,那么您将获得'Notice:Undefined property:stdClass :: SomeField'。 'FETCH_ASSOC'是否以不同的方式处理空值? – Nick
@Nick你是否为StdClass中的null属性设置了默认值? –
*您可以设置“StdClass”的默认值吗? – Nick