1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<sect1 xml:id="control-structures.match" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>match</title>
<?phpdoc print-version-for="match"?>
<para>
The <literal>match</literal> expression branches evaluation based on an
identity check of a value.
Similarly to a <literal>switch</literal> statement, a
<literal>match</literal> expression has a subject expression that is
compared against multiple alternatives. Unlike <literal>switch</literal>,
it will evaluate to a value much like ternary expressions.
Unlike <literal>switch</literal>, the comparison is an identity check
(<code>===</code>) rather than a weak equality check (<code>==</code>).
Match expressions are available as of PHP 8.0.0.
</para>
<example>
<title>Structure of a <literal>match</literal> expression</title>
<programlisting role="php">
<![CDATA[
<?php
$return_value = match (subject_expression) {
single_conditional_expression => return_expression,
conditional_expression1, conditional_expression2 => return_expression,
};
?>
]]>
</programlisting>
<example>
<title>Basic <literal>match</literal> usage</title>
<programlisting role="php">
<![CDATA[
<?php
$food = 'cake';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
string(19) "This food is a cake"
]]>
</screen>
</example>
<example>
<title>Example of using <literal>match</literal> with comparison operators</title>
<programlisting role="php">
<![CDATA[
<?php
$age = 18;
$output = match (true) {
$age < 2 => "Baby",
$age < 13 => "Child",
$age <= 19 => "Teenager",
$age >= 40 => "Old adult",
$age > 19 => "Young adult",
};
var_dump($output);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
string(8) "Teenager"
]]>
</screen>
</example>
<note>
<simpara>
The result of a <literal>match</literal> expression does not need to be used.
</simpara>
</note>
<note>
<simpara>
A <literal>match</literal> expression <emphasis>must</emphasis> be
terminated by a semicolon <literal>;</literal>.
</simpara>
</note>
</example>
<para>
The <literal>match</literal> expression is similar to a
<literal>switch</literal> statement but has some key differences:
<itemizedlist>
<listitem>
<simpara>
A <literal>match</literal> arm compares values strictly (<code>===</code>) instead
of loosely as the switch statement does.
</simpara>
</listitem>
<listitem>
<simpara>
A <literal>match</literal> expression returns a value.
</simpara>
</listitem>
<listitem>
<simpara>
<literal>match</literal> arms do not fall-through to later cases the way
<literal>switch</literal> statements do.
</simpara>
</listitem>
<listitem>
<simpara>
A <literal>match</literal> expression must be exhaustive.
</simpara>
</listitem>
</itemizedlist>
</para>
<para>
As <literal>switch</literal> statements, <literal>match</literal>
expressions are executed match arm by match arm.
In the beginning, no code is executed.
The conditional expressions are only evaluated if all previous conditional
expressions failed to match the subject expression.
Only the return expression corresponding to the matching conditional
expression will be evaluated.
For example:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$result = match ($x) {
foo() => ...,
$this->bar() => ..., // $this->bar() isn't called if foo() === $x
$this->baz => beep(), // beep() isn't called unless $x === $this->baz
// etc.
};
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
<literal>match</literal> expression arms may contain multiple expressions
separated by a comma. That is a logical OR, and is a short-hand for multiple
match arms with the same right-hand side.
</para>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$result = match ($x) {
// This match arm:
$a, $b, $c => 5,
// Is equivalent to these three match arms:
$a => 5,
$b => 5,
$c => 5,
};
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
A special case is the <literal>default</literal> pattern.
This pattern matches anything that wasn't previously matched.
For example:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$expressionResult = match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
default => baz(),
};
?>
]]>
</programlisting>
</informalexample>
<note>
<simpara>
Multiple default patterns will raise a
<constant>E_FATAL_ERROR</constant> error.
</simpara>
</note>
</para>
<para>
A <literal>match</literal> expression must be exhaustive. If the
subject expression is not handled by any match arm an
<classname>UnhandledMatchError</classname> is thrown.
</para>
<example>
<title>Example of an unhandled match expression</title>
<programlisting role="php">
<![CDATA[
<?php
$condition = 5;
try {
match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
};
} catch (\UnhandledMatchError $e) {
var_dump($e);
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
object(UnhandledMatchError)#1 (7) {
["message":protected]=>
string(33) "Unhandled match value of type int"
["string":"Error":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(9) "/in/ICgGK"
["line":protected]=>
int(6)
["trace":"Error":private]=>
array(0) {
}
["previous":"Error":private]=>
NULL
}
]]>
</screen>
</example>
<sect2>
<title>Using match expressions to handle non identity checks</title>
<para>
It is possible to use a <literal>match</literal> expression to handle
non-identity conditional cases by using <code>true</code> as the subject
expression.
</para>
<example>
<title>Using a generalized match expressions to branch on integer ranges</title>
<programlisting role="php">
<![CDATA[
<?php
$age = 23;
$result = match (true) {
$age >= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};
var_dump($result);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
string(11) "young adult"
]]>
</screen>
</example>
<example>
<title>Using a generalized match expressions to branch on string content</title>
<programlisting role="php">
<![CDATA[
<?php
$text = 'Bienvenue chez nous';
$result = match (true) {
str_contains($text, 'Welcome') || str_contains($text, 'Hello') => 'en',
str_contains($text, 'Bienvenue') || str_contains($text, 'Bonjour') => 'fr',
// ...
};
var_dump($result);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
string(2) "fr"
]]>
</screen>
</example>
</sect2>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
|