I’m having trouble understanding the behavior of php in a class with a typed variable, when I try to access the method even if it is null I get an error
<?php
class City
{
private string $id;
private string $name;
public function getId(): ?string
{
return $this->id;
}
public function setId(string $id): City
{
$this->id = $id;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): City
{
$this->name = $name;
return $this;
}
}
$city = new City();
$x = $city->getName();
I expected the same behavior as php whether or not the variable is typed
3
Answers
When a type is declared, all properties will have an uninitialized state. It is not allowed to access class properties prior to assigning an explicit value.
You can check if a class property is uninitialized using
isset($foo->name)
. Because this value is not the same asnull
, You cannot use$foo->name === null
to check if the property is uninitialized.In the above Code, If the $name property is uninitialized, This will throw an error:
If you give a class property a type that isn’t nullable and provide no default value, you’ll receive an error if the property’s value is accessed before being set.
You would need to change to:
In PHP, when you have a typed property (as of PHP 7.4) or a typed return type in a method, attempting to access that property or call that method on an instance with a null value can lead to a fatal error. PHP’s type system is strict, and it enforces type safety. If you specify a type for a property or method, PHP expects that the value will conform to that type. If it doesn’t, it raises an error.
we have a City class with a private property $name, which is initialized in the constructor. The getName() method is expected to return a string. When we create an instance of the City class with a valid name and then call getName(), it should work correctly.