[RFC] Properties in interfaces
| From: | Zoltán Fekete | Date: | Wed, 29 Mar 2023 19:53:56 +0000 |
| Subject: | [RFC] Properties in interfaces | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-119781@lists.php.net to get a copy of this message | ||
Hi,
[Proposal]
Allow interfaces to define properties. The implementing class must
have the same properties with the same name/type.
As the goal of the interfaces is to define the public "surface" of
the implementing class, I think that the public properties are also
part of that.
[Use case] - tl;dr;
Right now I’m working on a product configurator. The input I get, I
turn them into ValueObjects in the initial phase of the request. Then
later based on some conditions, I turn them in a deterministic but
very varying order into another ValueObject which has the same
properties, but all of them are
readonly. I tried to create somehow
the same: https://3v4l.org/Vb7fE#v8.2.4 There are places
where I
have an array with a mix of them and I want to access the $id or
$axisOrientation. I also have methods on them. I know an
abstract class could do this for me but I feel that this would be the
most accurate way to define what I want.
[Example]
```php
interface Vehicle {
public int $serialNumber;
public function drive(): void;
}
/*
* This would lead to an error, something like:
* Class Car contains 1 abstract property and must therefore be
* declared abstract or implement the remaining property
* (Vehicle::$serialNumber)
*/
class Car implements Vehicle {
public function drive() : void { }
}
// This would lead to an error too, because the type is different.
class Bike implements Vehicle {
public string $serialNumber;
public function drive() : void { }
}
// This would lead to an error too. The rule for readonly properties
// would be the same as right now between normal classes.
class Bike implements Vehicle {
public readonly string $serialNumber;
public function drive() : void { }
}
```
[Implementation]
Personally I don’t have experience in php internal development.
I do have C++ / some C experience. I'm going through the PHP
Internals book and every possible tutorial I find. I definitely would
like to take part in it, and I'm planning to do more later.
--
Bests
Zoltán Fekete