So, #PHP typed class constants are vaguely useful?

Here is a nice usage case that will definitely makes everyone love them.

#phptip #phptrick

https://php-tips.readthedocs.io/en/latest/tips/crazy_const_type.html

@dseguy I'm not sure how to feel about that.

@lordmatt I'm writing a rule to spot and eradicate it.

But, as the saying goes, if there is a mean, there is a will. 😜

@dseguy Important feature!

We wouldn't want to confuse tooling with invalid type definitions, now would we:

<?php

if (random_int(0, 1)) {
class A {
const int|float X = 42;
}
} else {
class A {
const int|float X = 42.0;
}
}

var_dump(A::X);

/s

@dseguy real talk - typed constants have been more useful than the entire Enum feature added a few releases back.

@bobmagicii I'd say my experience is opposite, enum are more useful than typed const Both are cool features, in any case.

Enum limit values and scope of any equivalent constant, leading to easier to understand code. Sometimes, it leads to more conversion, but not so much.

Can you elaborate?

@dseguy i refuse to type "$Enum->value" basically.
@bobmagicii A yes, the occasional conversion. I see. Thanks.

@dseguy if you say so. there were zero instances where i could make enum's do anything without doing it. their api is just gross and why doesn't it have like a __toValue() magic method. now, typed consts, on a proper struct. 🤌

$EnumInt->value //weak

// things it seemly could not do
(int)$EnumInt // stronk forced __toValue
echo $EnumInt // magic __toValue
sprintf('you picked %d', $EnumInt); // i can keep going