你可以使用instanceof:
if ($pdo instanceof PDO) {
// it's PDO
}
但请注意,您不能像 !instanceof 那样否定,所以您应该这样做:
if (!($pdo instanceof PDO)) {
// it's not PDO
}
此外,查看您的问题,您可以使用对象类型提示,这有助于强制执行要求并简化您的检查逻辑:
function connect(PDO $pdo = null)
{
if (null !== $pdo) {
// it's PDO since it can only be
// NULL or a PDO object (or a sub-type of PDO)
}
}
connect(new SomeClass()); // fatal error, if SomeClass doesn't extend PDO
类型化的参数可以是必需的或可选的:
// required, only PDO (and sub-types) are valid
function connect(PDO $pdo) { }
// optional, only PDO (and sub-types) and
// NULL (can be omitted) are valid
function connect(PDO $pdo = null) { }
无类型参数允许通过显式条件实现灵活性:
// accepts any argument, checks for PDO in body
function connect($pdo)
{
if ($pdo instanceof PDO) {
// ...
}
}
// accepts any argument, checks for non-PDO in body
function connect($pdo)
{
if (!($pdo instanceof PDO)) {
// ...
}
}
// accepts any argument, checks for method existance
function connect($pdo)
{
if (method_exists($pdo, 'query')) {
// ...
}
}
至于后者(使用method_exists),我的看法有点复杂。来自 Ruby 的人会发现 respond_to? 熟悉它,无论好坏。我会亲自编写一个接口并针对它执行正常的类型提示:
interface QueryableInterface
{
function query();
}
class MyPDO extends PDO implements QueryableInterface { }
function connect(QueryableInterface $queryable) { }
但是,这并不总是可行;在此示例中,PDO 对象不是有效参数,因为基类型未实现 QueryableInterface。
还值得一提的是,值在 PHP 中具有类型,而不是变量。这很重要,因为null 将无法通过instanceof 检查。
$object = new Object();
$object = null;
if ($object instanceof Object) {
// never run because $object is simply null
}
当它变成null时,该值失去了它的类型,缺少类型。