-
Notifications
You must be signed in to change notification settings - Fork 8k
Description
I would like to request the addition of a syntax feature in PHP that allows grouping multiple properties with the same type in a class, improving code readability and reducing repetition in class definitions. This feature would be similar to the ability to declare properties in a single line with type hints introduced in PHP 7.4, but with the added flexibility to group them logically by type.
For a long time we have been able to do:
class SimplePlural {
private
$name = 'Plural', // separate by commas
$value = 0,
$isTrue = false,
$array = [],
$object,
$noType;
}
As long as we didn't give it a typed property, but since 7.4 we had to declare the visibility modifiers every time if we wanted to have typed properties on them.
class Singular {
private string $name = 'Singular';
private int $value = 0;
private bool $isTrue = false;
protected array $array = [];
protected object $object;
protected $noType;
}
The Proposal
Grouped Property Declarations with Type Hints
PHP currently supports declaring properties either with type hints introduced in PHP 7.4 or without type hints using a grouped style. However, a hybrid syntax combining both would simplify code readability and maintenance.
A mixture of both.
class Plural {
private
string $name = 'Plural', // separate by commas
int $value = 0,
bool $isTrue = false;
protected
array $array = [],
object $object,
$noType;
}
A bit similar to, but without the type grouping.
class Series {
private string
$n = 'Se', // separate by commas
$m = 'ri',
$s = 'es';
private int
$v = 0,
$u = 1,
$e = 2;
private bool
$t = true,
$f = false;
private array
$a = [],
$r = [1, 2, 3];
private object
$o,
$b;
}
Benefits:
Improved readability: Grouping related properties by type would make class definitions easier to scan, especially in larger classes.
Reduced repetition: Reduces the need to repeat the type declaration for each property, making the code more concise.
Better maintainability: It's easier to spot and manage changes for properties that share the same type.
And it would also be nice if we could create simple JSON-like objects directly instead of building them in __construct() and why not allow { } to create objects instead of (object) [ ]? It is something we are used to from JSON.
Thanks and happy coding!