In a table class I can run the below code and it saves the entity with whatever property values I’ve modified in modifyMyEntity.
My question is should I be defining modifyMyEntity to receive $entity by reference as in public function modifyMyEntity(EntityInterface &$entity) or given that it works without passing by reference not worry about it?
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options): void
{
$this->modifyMyEntity($entity);
}
public function modifyMyEntity(EntityInterface $entity): void
{
$entity->my_property = "Updated value";
}
Objects are passed by reference by default in PHP. Only primitive types (like int, bool, string, etc.) ever need to have the & added to them if you want to modify them in the function and have that modification survive back to the caller.
Consider, if you had to add the & to your modifyMyEntity function in order for the changes to get back to beforeSave, how do those changes then get back to whoever calls beforeSave without also changing the signature of that function? Which you’re not allowed to do because then it won’t match the base class.
Thank you! Before I posted my question I Googled “PHP References” and got this page: PHP: Passing by Reference - Manual which didn’t explain it for me.