I recently saw a project that uses null
as a default value on class properties, specifically entities.
For example
class SomeEntity
{
private ?int $id = null;
public function getId(): ?int
{
return $this->id;
}
public function setId(int $id): void
{
$this->id = $id;
}
}
Notice that the setter setId(int $id)
does not allow null values.
Is there any particular advantage to having this setup? Why not have no value properties? I can’t think of any benefits(or drawbacks for that matter) to having default null
or no default.
3
Answers
This is a new trend – making default behavior more obvious. You can ignore it if it’s already obvious to you.
It will produce an error if you access the
property
that don’t have a default value when its not initialized.Let’s say you want to override the value of
property
depending on its current value.If we use the
getId()
without the default value of null it will produce an error.As it said;
setId(int $id)
not allowing null values, because this enforces rule that ID must always be an integer and nevernull
. This can be important for maintaining data integrity, especially in systems where the ID is used as a unique identifier for the entity.In contrast, not providing a default value means that the property is uninitialized until it’s explicitly set. This can lead to issues if the property is accessed before being set, potentially resulting in errors or warnings about accessing uninitialized properties. So, whether to use
null
as a default value or not, depends on the specific requirements of your application and how you want to handle the absence of a value, Both approaches have their merits and potential drawbacks, and the best choice depends on the context in which they are used.