[PHP-DEV] Re: Empty subject in match and switch constructions

On Feb 2, 2025, at 4:04 PM, Dmitry Derepko xepozzd@gmail.com wrote:

Hi!

I’m thinking about making match (true) and switch (true) be more lightweight by removing the subject “(true)” and making matching “true condition” by default.
So $var = match (true) { … } can be used as $var = match { … }.

It’s often used in Kotlin. Pretty convenient way to use combined conditions. It’s natively understandable because there should be a condition:

$result = match {
$x < $n => …,
$x > $n => …,
else => …,
}

The same explanation for switch construction, but in Kotlin it’s the same construction “when":

val result = when {
x < n → …
x > n → …
else → …
}

var result = null

when {
x < n → { result = … }
x > n → { result = … }
else → return
}

[

<docs.png>

Conditions and loops
kotlinlang.org

](https://kotlinlang.org/docs/control-flow.html#when-expressions-and-statements)

when construction is overwhelming, but some features are totally handy, such as checking for class of the subject:
when (obj) {
is Class1 → …
is Class2 → …
else → …
}

Which was implemented by Ilija Tovilo in: https://github.com/php/php-src/compare/master…iluuu1994:pattern-matching

By the way, what do you think about allowing to drop the subject of match / switch as a first iteration?
Maybe would be better to ask Ilija to recreate his PR?


Best regards,
Dmitrii Derepko.
@xepozz

I would like to bring the discussion up and try to figure out all pros and cons of this ability.
Moreover, coming Pattern Matching is a great addition to have this merged:

$x = match {
$a is “pattern” → …
$b is “pattern” → …
$c === null → …
$this->lastChance($d) → …
default → …
}

Again, it should work as it would have (true) context. So the following snippet:

var_dump(match(true) {
1=>‘one’,
0=>‘zero’,
default=>‘default’,
});

will produce “default”, because “true” is not “1” and “0”.

IDE may highlight such cases because they’ll never match so it would be detected as dead code.


Best regards,
Dmitrii Derepko.
@xepozz