Hack: How to clone a shape

Date: 2019-08-05 | hack | php | shape | tutorial |

problem

I'm writing Hack (that PHP variant) and trying to figure out how to clone an object / shape such that I can modify my new version without affecting the old version. I've searched through the standard libraries and couldn't find anything that looked like it had this functionality. How do I do this?

solution

The key is that objects aren't really referenced by new variables, rather they're aliased by them. For instance, let's say I have an object type of ValHolder that just has a value in it. If I create a var with a new one, then create a new var that is assigned to the old var, then change the val of the new var, the old var will be unaffected.

Example:

$a = new ValHolder(5); // we'll say that this sets the internals of ValHolder to 5
$b = $a;
$b->setValue(10);

echo "$a = ";var_dump($a->getValue()) // 5
echo "$b = ";var_dump($b->getValue()) // 10

did this help?

I regularly post about tech topics I run into. You can get a periodic email containing updates on new posts and things I've built by subscribing here.

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.