myol myol - 7 months ago 39
PHP Question

Equal to a new ArrayObject

I have a variable that is assigned as a new


$var = new ArrayObject();

I want to check if this variable is of type
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.

simple returns
which is of no use.

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'; }


You can use the method serialize of ArrayObject to check:

See the following code (

$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());