I have a method which accepts a PDO object as an argument, to allow the user to use an existing connection rather then the method to open a new one, and save resources:
public static function databaseConnect($pdo = null) {
I am aware of is_object()
to check if the argument is an object, but I want to check if $pdo
is a PDO object, and not just an object.
Because the user can easily enter (by mistake?) a different kind of object, a mysqli or such, and the entire script will break apart.
In short: How can I check a variable for a specific type of object?
You can use
instanceof
:Be aware though, you can't negate like
!instanceof
, so you'd instead do:Also, looking over your question, you can use object type-hinting, which helps enforce requirements, as well as simplify your check logic:
Typed arguments can be required or optional:
Untyped arguments allow for flexibility through explicit conditions:
As for the latter (using
method_exists
), I'm a bit mixed in my opinion. People coming from Ruby would find it familiar torespond_to?
, for better or for worse. I'd personally write an interface and perform a normal type-hint against that:However, that's not always feasible; in this example,
PDO
objects are not valid parameters as the base type doesn't implementQueryableInterface
.It's also worth mentioning that values have types, not variables, in PHP. This is important because
null
will fail aninstanceof
check.The value loses it's type when it becomes
null
, a lack of type.