myol myol - 22 days ago 7
PHP Question

Equal to a new ArrayObject

I have a variable that is assigned as a new

ArrayObject


$var = new ArrayObject();


I want to check if this variable is of type
ArrayObject
and is in a newly instantiated state (same property values and structure). One way seems to be using non strict evaluation
==
instead of
===


if ($var == new ArrayObject) { echo 'true'; }


Given the crazy gotchas of PHP I don't know if
==
is just checking if both are simply objects or what. I want a more strict way of checking.

gettype
simple returns
Object
which is of no use.

EDIT:
is_a()
seems to detect the type correctly but how then can I check if $var is in a newly instantiated state?

if (is_a($var, 'ArrayObject')) { echo 'true'; }

Answer

You can use the method serialize of ArrayObject to check:

See the following code (http://ideone.com/Frx0EH):

$arr1 = new ArrayObject([1,2,3]);
$arr2 = new ArrayObject();
$arr3 = 'HelloWorld';

var_dump(isInitArrayObject($arr1)); //false
var_dump(isInitArrayObject($arr2)); //true
var_dump(isInitArrayObject($arr3)); //false

function isInitArrayObject($arr1) {
    if (!($arr1 instanceof ArrayObject)) {
        return false;
    } else {
        $arr_init = new ArrayObject();
        return ($arr1->serialize() === $arr_init->serialize());
    }
}