我在名为Connection
的类中有以下方法:
public function output($query = null) {
if (!empty($this->attributes["link"])) {
print "OK!";
} else {
print "NO!";
}
}
$this->attributes["link"]
的值来自构造函数中的以下操作:
try {
$this->attributes["link"] = new \PDO(<...>);
catch (\PDOException $e) {
<...>
} finally {
return $this;
}
我通常使用if (!empty(<...>)) { <...> }
构造来测试变量的存在性,到目前为止,它在每个结构或代码段中都按预期工作,除了这个。
作为一个对象似乎不是一个不工作的原因,因为我可以对数据库管理器对象测试相同的检查,并且它的工作原理。也许PDO对象是一种特殊的对象,不容易进行变量测试,或者是否有我遗漏的东西?
编辑 - 我的软件配置如下:Linux 3.11.1,Apache 2.4.6,PHP 5.5.4和MySQL 5.6.13
答案 0 :(得分:0)
为什么不检查是否是PDO实例?
if ($this->attributes['link'] instanceof \PDO) {
// ...
} else {
// ...
}