brianhaveri/Underscore.php

Memoize default hashFunction can't recognize different Closures

Opened this issue · 1 comments

Simple example first:

<?php
$foo = function($no) {
  return "Foo: {$no}\n";
};

$bar = function($no) {
  return "Bar: {$no}\n";
};

$foo_mem = __::memoize($foo);
$bar_mem = __::memoize($bar);

echo $foo_mem(5);
echo $bar_mem(5);

The output of this script is:

$ php test.php
Foo: 5
Foo: 5

It's because var_export can't properly export Closure's. It's better to use spl_object_hash() in hash function.
I have simple (and yet stupid) example of hash function:

<?php
$hash = function($function, $args) {
  return md5(join('_', array(
    spl_object_hash($function),
    var_export($args, true),
  )));
};

$foo = function($no) {
  return "Foo: {$no}\n";
};

$bar = function($no) {
  return "Bar: {$no}\n";
};

$foo_mem = __::memoize($foo, $hash);
$bar_mem = __::memoize($bar, $hash);

echo $foo_mem(5);
echo $bar_mem(5);

Maybe it's time to implement better default hash function? What do You think about it?
In free time, I'll try to propose my implementation of it.

Ah, forgot to write. The issue is on PHP 5.3.8