Search code examples
symfonymodel-view-controllerdoctrine-ormentitysymfony4

Symfony 4 Entity getter and setter return values


When I get values from database where the field is null I get the below error.

Return value of App\Entity\Settings::getDescription() must be of the type string, null returned

The value is saved as null. Below is get method of the field.

public function getDescription(): string
{
    return $this->description;
}

When I remove the code after "colon" I do not get the above error. Any workaround to solve this issue ?


Solution

  • You are specifying a return type string which the value null does not match. Besides removing the return type entirely, there are many ways to deal with this:

    1. Make the return type optional

      public function getDescription(): ?string
      

    This will allow null or a string, which instantly fixes your problem. The downside is, that whenever you call getDescription() you might have to deal with this null leading to ugly code like this:

    $description = $entity->getDescription();
    if (null === $description) {
        // Do something with null
    }
    // Do something
    

    With a description this is likely not a problem. If you have some other data like a DateTime receiving null can be problematic if you want to format the datetime or compare it with another datetime-value.

    This is why the second option could make sense:

    1. Ensure the value is filled:

      public function getDescription(): string
      {
          return$this->description ?? '';
      }
      

      or:

      private $description = '';
      
      public function getDescription(): string
      {
          return$this->description;
      }
      

    This or other methods make sure that whenever the database value is not set, it will use a default value, e.g. an empty string. This might not always make sense.

    There are other ways to deal with this, but whether they make sense largely depends on the context you are working in. Those 2 above are pretty common ways around your problem: nullable return type or an explicit default value defined in your db or in your code instead of null.