PHP 8.3 and Interface Properties #10518
-
Alright I've thrown together a half-ass recreation in the Playground but it's hard to do the full thing without basically copy-pasting a ton of Laravel classes. But I for the life of me cannot figure out why PHPStan doesn't see these properties. https://phpstan.org/r/58cdf392-e5a0-4915-aaff-cec675b5e27c I tried following this section of the docs but it doesn't seem to match or work with how we are doing things. I can't tell if this is a "you're doing it wrong" issue or a "phpstan is being weird" issue https://phpstan.org/blog/solving-phpstan-access-to-undefined-property#making-%40property-phpdoc-above-interfaces-work-on-php-8.2%2B What we're trying to accomplish is a shared interface that objects implement the interface with defined properties as they are shared across all implementing objects. I'm starting to think this is an issue of "just use an abstract class" but we don't really need an abstract class in this implementation. Am I just approaching this completely wrong as I try to make more type safe PHP code? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
What class in the end implements |
Beta Was this translation helpful? Give feedback.
-
You have two options:
|
Beta Was this translation helpful? Give feedback.
You should typehint
Hvac\AttributeCost|Siding\AttributeCost
instead of theAttributeCosts
interface. That would make the problem go away.If there's a lot of classes like that, you can create a type alias: https://phpstan.org/writing-php-code/phpdoc-types#local-type-aliases
The problem is that you can't declare properties on interfaces. So
@property
above an interface does not enforce anything. It's a hack and you're better off getting rid of it :)