Re: Multiple property assigning without constructor
| From: | Vinicius Dias | Date: | Wed, 04 Dec 2024 17:41:40 +0000 |
| Subject: | Re: Multiple property assigning without constructor | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-126101@lists.php.net to get a copy of this message | ||
> But often classes need constructors only to set properties. In such cases, constructors become
> redundant.
Actually, the behavior is not the same and the constructors are not redundant.
Taking your example:
```
class Person
{
public string $firstName;
public int $age;
}
$person = new Person {
firstName: "John",
age: 42
};
```
This would allow the following:
```
$invalidPerson = new Person();
```
Now we have a person without name or age. But with constructors we
make sure that the object is always in a valid state:
```
class Person
{
public function __construct(public string $firstName, public int $age)
{ }
}
$validPerson = new Person('Name', 40);
$invalidPerson = new Person(); // this is impossible. every person
needs firstName and age
```
I just wanted to point that out. :-)