Hack: Memoize doesn't play nice with LSB
See example run: https://3v4l.org/fKi0j
<?hh
class A {
protected static string $string = 'Hello';
<<__Memoize>>
public static function foo(): string {
return static::$string;
}
}
class B extends A {
protected static string $string = 'World';
}
I'd expect B::foo() to return 'World' in this case, whereas it returns Hello.
I'm fairly certain this is by design. __Memoize caches are keyed based only on parameters, and an extending class doesn't have its own cache for memoized statics in the parent.
Yeah, I suspect this is wontfix, poke @dlreeves @dabek and @int3 just in case.
If that's the case, should static:: usage throw an error in a __Memoize method?
Have managed to work around this with a nasty hack:
<?hh
class A {
protected static string $string = 'Hello';
<<__Memoize>>
public static function foo($class = get_called_class()): string {
// UNSAFE
return $class::$string;
}
}
class B extends A {
protected static string $string = 'World';
}
Is slightly nicer than how we've been polluting the global namespace with a bunch of functions that are basically:
<<__Memoize>>
function getMemoizedB(): string {
return B::foo();
}
An actual solution will be nicer though.
This topic tends to come up from time to time internally. The consensus now seems to be that both behaviors are potentially surprising (one could easily assume the memoization was per declaration site or per LSB target).
Changing __Memoize is unlikely to be a viable option as we've found that most of the time the LSB isn't something we care about, but adding a __MemoizedLSB has been proposed a few times and is generally something I'd be in favor of adding (though I've not had time to poke at it myself).
3.28 includes <<__MemoizeLSB>> as an experimental feature