Reputation: 3984
in php 7.4, i can now define class property types: So instead of:
class A{
/** @var string */
protected $string;
}
i can now do:
class A{
protected string $string;
}
so, is it worthwhile to do this? ie, is it worth recoding my code base to use this feature?
is there a performance boost?
Upvotes: 2
Views: 334
Reputation: 33238
It's not about performance, typed properties are meant to enforce type contracts in your code. It's difficult to say if there is any performance difference, whether positive or negative, but the performance should not be the reason why you should specify types.
You already use PHPDoc comments, which means that it is important for you to know what type the property should be, but PHPDoc block does not enforce it. This code is perfectly valid:
<?php
class A {
/** @var int */
public $number;
}
$a = new A();
$a->number = 'a';
echo $a->number;
With typed properties, you tell PHP runtime to check the type before assignment or usage. PHP will not allow type mismatch. This code will throw an error:
<?php
class A {
public int $number;
}
$a = new A();
$a->number = 'a';
echo $a->number;
Fatal error: Uncaught TypeError: Cannot assign string to property A::$int of type int
Upvotes: 1