How do you compare classes that contain `Closure`?

618 Views Asked by At

So, how do you compare classes that contain Closure ? It looks like you can't.

class a {
    protected $whatever;
    function __construct() {    
        $this->whatever = function() {};
    }
}

$b = new a();
$c = new a();

var_dump( $b == $c );   //false
1

There are 1 best solutions below

2
Rizier123 On

Well you can't serialize() closures straight on, but you can do a workaround, since serialize() invokes __sleep() when it's serializing objects, so it gives the object to option to clean things up! This what we're doing here:

class a {

    protected $whatever;

    function __construct() {    
        $this->whatever = function() {};
    }

    public function __sleep() {
        $r = [];
        foreach ($this as $k => $v){
            if (!is_array($v) && !is_string($v) && is_callable($v))
                continue;
            $r[] = $k;
        }
        return $r;
    }

}

So now you can use serialize() with md5() to compare your objects like this:

var_dump(md5(serialize($b)) === md5(serialize($c))); 

output:

bool(true)