php - Update array key based on value change -
given have object
$obj = new stdclass(); $obj->name = 'my-object';
and object stored thusly
$store = [ $obj->name => &$obj ];
is there way change store key when property changes?
$obj->name = 'new-name'; // $store['new-name'] not set, $store['my-object'] still
edit:
thanks scott pointing out shouldn't store them way. here's came with. there's overhead here, it's core function.
$obj1 = new stdclass(); $obj1->name = 'my-object'; $obj2 = new stdclass(); $obj2->name = 'another-object'; $store = [ $obj1, $obj2 ]; $key = 'my-object'; $result = array_filter($store, function ($obj) use ($key) { return ($obj->name == $key); }); // results in: [$obj1]
you shouldn't store value change. use unique identifier or guid.
if can't (which should) make name property private , use setname()
function. within function, find object store, remove old object, change name, add object new name. because object needs know store, have more tightly coupled code (that's bad, maybe necessary).
Comments
Post a Comment