Prevent spooky-action-at-a-distance by runtime ownership check using refcount
As an alternative design pattern to immutable objects, you can also check an object’s refcount to make sure it’s less than 2.
class Foo {
public function __set($name, $val) {
// if refcount > 1, throw exception
}
}
$foo = new Foo();
$foo->prop = 'something';
// ... more initialisation
dosomething($foo); // Function cannot set a prop
This pattern is usable for dependency injection where the setup is more complicated than in an immutable object, but access should be limited for dependent classes (e.g. not being able to close a database connection).
Here’s one way to check refcount (from stackoverflow):
function refcount($var)
{
ob_start();
debug_zval_dump($var);
$dump = ob_get_clean();
$matches = array();
preg_match('/refcount\(([0-9]+)/', $dump, $matches);
$count = $matches[1];
//3 references are added, including when calling debug_zval_dump()
return $count - 3;
}