Function to check for value prior to using getValue? I'm trying to write a function that takes into account both regular text fields and entity references and checks for a value prior to using getValue() to assign it to a variable. 

   function checkUserFieldAvailability($fieldName, $assignedName){
      if (!$user-&gt;get($fieldName)-&gt;isEmpty()) {
        ${$assignedName} = $user-&gt;get($fieldName)-&gt;first()-&gt;getValue()['target_id'];
      }
      else {
        ${$assignedName} = "";
      }
    }


Something like this... Is there an easy way to make it account for both entity references that are assigned like this...

$name = $user-&gt;get('field_firstname')-&gt;first()-&gt;getValue()['target_id'];


and regular text fields which are assigned like this.

$email = $user-&gt;get('mail')-&gt;getValue();


Basically i'm trying to confirm all the fields I'm making assignments too in fact first have a value (to avoid errors) and if not assing  an empty string.
I think you are looking for the main property of the field:

if ($item = $user-&gt;get($fieldName)-&gt;first()) {
  $string = $item-&gt;{$item-&gt;mainPropertyName()};
}
else {
  $string = '';
}