PHP 7.4 Typed Properties BC Problems
Updated: April 25, 2024 20:52
Published: December 27, 2019 02:13
If you’re not aware, PHP 7.4 has introduced Typed Properties. But buyer beware, there‘s a hitch...
Prior to PHP 7.4, declaring property scalar types was done with DocBlocks as follows:
With typed properties introduced in PHP 7.4, the scalar type can now be set like this:
This is awesome, it cuts down on excessive boilerplate and the PHP interpreter will not allow an invalid value to be set on the property.
But, there are a couple caveats to be aware of...
Without setting a property type, one would be able to have a class property such as:
And then call the property without any problems like:
However, if you declare the property type and then attempt to access that type as above, you'll get a FatalError. I.e.
To overcome this, you must set the value of $id
before attempting to access it. This can be accomplished in a number of ways.
Using any of the above means of setting $id
before
accessing the value of $id
would result in the
following:
Of course if you are using setter's to set the value of
$id
, you must call the setter method
before accessing the property.
[email protected]