Improving Code Using Typed Properties
Learn about typed properties and how they assign data types to variables and arguments.
We'll cover the following...
Earlier, we discussed how data types can be used to control the type of data supplied as arguments to functions or class methods. What this approach fails to do, however, is guarantee that the data type never changes. In this lesson, we will learn how assigning a data type at the property level provides stricter control over the use of variables in PHP 8.
What are typed properties?
This extremely important feature was introduced in PHP 7.4 and continues in PHP 8. Simply put, a typed property is a class property with a data type preassigned. Here is a simple example:
Press + to interact
<?php// Creating a Test classdeclare(strict_types=1);class Test{public int $id = 0;public int $token = 0;public string $name = '';}// Creating object of Test class$test = new Test();$test->id = 'ABC';// causes Fatal Error?>
In this ...