Programmatically append values to entity reference field of node with a dynamic field name I understand that I can append values to an entity reference field to a node normally with this method

$node-&gt;field_tags[] = [
    'target_id' =&gt; $my_id,
  ];


However I have a function like so

function addTag($node,$field,$id){
$node-&gt;set($field,[
    'target_id' =&gt; $id,
  ]);
}


In other words I have to anticipate any field the user supplies. Looking at the node class here

https://api.drupal.org/api/drupal/core!modules!node!src!Entity!Node.php/class/Node/8.2.x

I did discover the set function that lets me specify a field and a value but I don't believe that this would append to an array of entities in a field.

How would I append to an entity reference field to a node if the field name is supplied in a variable?
Yes, the class Node is a good starting point to look for an OOP way:

Click on get(), which returns a field object FieldItemList, where you can use the method appendItem():

$node-&gt;get($field)-&gt;appendItem([
  'target_id' =&gt; $id,
]);


Replace -&gt;get() with {} and -&gt;appendItem() with [] and you get the shorter version which @Clive mentioned in the comment:

$node-&gt;{$field}[] = $id;


This is possible because of the  magic method ContentEntityBase::__get and the ArrayAccess interface the field implements. I've also dropped target_id, because you don't need this for the main property of a field.