Hello @kartik,
You can use instanceof:
if ($pdo instanceof PDO) {
// it's PDO
}
Be aware though, you can't negate like !instanceof, so you'd instead do:
if (!($pdo instanceof PDO)) {
// it's not PDO
}
Also, looking over your question, you can use object type-hinting, which helps enforce requirements, as well as simplify your check logic:
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
Typed arguments can be required or optional:
// 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) { }
Untyped arguments allow for flexibility through explicit conditions:
// 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')) {
// ...
}
}
Hope it helps!!