您可以使用instanceof http://www.php.net/manual/en/language.operators.type.php:
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')) {
// ...
}
}
至于后者(using method_exists http://php.net/manual/en/function.method-exists.php),我的看法有点复杂。来自 Ruby 的人会发现它很熟悉respond_to? http://ruby-doc.org/core-2.1.1/Object.html#method-i-respond_to-3F, 不管是好是坏。我个人会编写一个接口并针对该接口执行正常的类型提示:
interface QueryableInterface
{
function query();
}
class MyPDO extends PDO implements QueryableInterface { }
function connect(QueryableInterface $queryable) { }
然而,这并不是always可行的;在这个例子中,PDO
对象不是有效参数,因为基本类型未实现QueryableInterface
.
还值得一提的是值有类型在 PHP 中,不是变量。这很重要,因为null
将会失败instanceof
check.
$object = new Object();
$object = null;
if ($object instanceof Object) {
// never run because $object is simply null
}
当值变成时,它就失去了它的类型null
,缺乏类型。