Please wait

Typed Properties

Typed properties in PHP are class properties that have a specific data type declared. This means that you specify what type of value a property can hold when you declare the property in your class. This feature is available as of PHP 7.4.

Prior to PHP 7.4, you could declare class properties (variables), but you could not specify what type of data they were expected to hold. With the introduction of typed properties, you can specify the data type of your class properties.

Typed properties enhance the reliability and readability of your code. They ensure that properties contain values of the correct type, which can prevent bugs. They also make your code easier to understand because you can see the expected data type of each property.

Applying types

Here's an example of typed properties in a class:

class Book {
  public string $title;
  public int $yearPublished;
}

In this example, the Book class has two properties, $title and $yearPublished. The $title property is expected to be a string, and $yearPublished is expected to be an integer. If you try to assign a value of a different type to these properties, PHP will throw an error.

Strict types

By default, PHP attempts type coercion/type juggling if we attempt to pass in a value with the incorrect type. For example, take the following:

$myBook = new Book();
$myBook->yearPublished = "1999";
 
var_dump($myBook->yearPublished); // int(1999)

In this example, a new instance of the Book class is created and stored in a variable called $myBook. Next, we updated the $yearPublished property to a string even though the data type is int. Behind the scenes, PHP type juggles the string into an integer.

We can prevent this behavior by enabling strict typing. To enable strict typing, you declare this at the top of your PHP file with the declare(strict_types=1); directive. This means that PHP will enforce the exact type for function arguments and return statements.

declare(strict_types=1);
 
class Book {
  public string $title;
  public int $yearPublished;
}

Now if you attempt the same code example:

$myBook = new Book();
$myBook->yearPublished = "1999";  // throws error
 
var_dump($myBook->yearPublished);

PHP throws an error if we were to set the property to a value with an incorrect type.

Key Takeaways

  • Typed properties are class properties in PHP that have a specific data type declared. This feature is available as of PHP 7.4.
  • Once a property has a type declared, PHP will enforce that the property contains a value of the correct type.
  • Strict typing applies to typed properties. Typed properties will throw an error if you assign a value of the wrong type.
  • Typed properties enhance the reliability and readability of your code by ensuring properties contain values of the correct type and by making it clear what type of data each property is expected to hold.

Comments

Please read this before commenting