How to Check for a Specific Type of Object in PHP

How to Check for a Specific Type of Object in PHP

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')) {
// ...
}
}

As for the latter (using method_exists), I'm a bit mixed in my opinion. People coming from Ruby would find it familiar to respond_to?, for better or for worse. I'd personally write an interface and perform a normal type-hint against that:

interface QueryableInterface
{
function query();
}

class MyPDO extends PDO implements QueryableInterface { }

function connect(QueryableInterface $queryable) { }

However, that's not always feasible; in this example, PDO objects are not valid parameters as the base type doesn't implement QueryableInterface.

It's also worth mentioning that values have types, not variables, in PHP. This is important because null will fail an instanceof check.

$object = new Object();
$object = null;
if ($object instanceof Object) {
// never run because $object is simply null
}

The value loses it's type when it becomes null, a lack of type.

get type in php returns object and not the object type

Just to explain why gettype() doesn't work as expected since others have already provided the correct answer. gettype() returns the type of variable — i.e. boolean, integer, double, string, array, object, resource, NULL or unknown type (cf. the gettype() manual link above).

In your case the variable $campaign is an object (as returned by gettype()), and that object is an instance of the class Campaign (as returned by get_class()).

How can I check if a object is an instance of a specific class?

You can check if an object is an instance of a class with instanceof, e.g.

if($role instanceof SimpleXMLElement) {
//do stuff
}

How to search objects to see if they contain a specific value?

To check if the name property exists in an object:

if(isset($obj->name)) {
// It exists!
}

So, if you want to find those objects that had $name properties:

$result = array_filter($myArray, function($x) {
return isset($x->name);
}); // Assuming PHP 5.3 or higher

Can I check if an object is kind of a specific class, in PHP?

You can use the instanceof operator, to check if an object is an instance of :

  • A class
  • Or a child class of that class
  • Or an instance of a class that implements an interface

Which means that it cannot be used to detect if your object is an instance of a specific class -- as it will say "yes" if your object is an instance of a child-class of that class.


For instance, this portion of code :

class ClassA {}
class ClassB extends ClassA {}

$a = new ClassB();
if ($a instanceof ClassA) {
echo '$a is an instanceof ClassA<br />';
}
if ($a instanceof ClassB) {
echo '$a is an instanceof ClassB<br />';
}

Will get you this output :

$a is an instanceof ClassA
$a is an instanceof ClassB

$a, in a way, is an instance of ClassA, as ClassB is a child-class of ClassA.

And, of course, $a is also an instance of ClassB -- see the line where it's instanciated.

way to specify class's type of an object in PHP

In addition to the TypeHinting already mentioned, you can document the property, e.g.

class FileFinder
{
/**
* The Query to run against the FileSystem
* @var \FileFinder\FileQuery;
*/
protected $_query;

/**
* Contains the result of the FileQuery
* @var Array
*/
protected $_result;

// ... more code

The @var annotation would help some IDEs in providing Code Assistance.

PHP: Ensure that an array contains objects from only a certain class

You could use array_map or array_walk for this:

https://php.net/manual/en/function.array-map.php

Example of array_map:

function isInstanceOfFoo($n)
{
if(!($n instanceof Foo)) {
throw new Exception('Error');
}
}

$ArrayObject = Array();

array_push($ArrayObject, new Foo());
array_push($ArrayObject, new Foo());
array_push($ArrayObject, new ErrorFoo());

array_map(isInstanceOfFoo, $ArrayObject);

https://php.net/manual/en/function.array-walk.php

Example of array_walk:

function isInstanceOfFoo($n, $k)
{
if(!($n instanceof Foo)) {
throw new Exception('Error');
}
}
array_walk($ArrayObject, isInstanceOfFoo);

how to check if methods parameter is a stdClass Object

Well solution look like easy one.

public function hello(stdClass $row)

I checked with php version 5.3 it works. like passing a stdclass object works but all other types gave cacheable fatal error.



Related Topics



Leave a reply



Submit