|
28 | 28 | Note that class constants are allocated once per class, and not for each
|
29 | 29 | class instance.
|
30 | 30 | </para>
|
| 31 | + <para> |
| 32 | + As of PHP 8.3.0, class constants can have a scalar type such as <literal>bool</literal>, |
| 33 | + <literal>int</literal>, <literal>float</literal>, <literal>string</literal>, or even |
| 34 | + <literal>array</literal>. When using <literal>array</literal>, the contents can only be |
| 35 | + other scalar types. |
| 36 | + </para> |
31 | 37 | <example>
|
32 | 38 | <title>Defining and using a constant</title>
|
33 | 39 | <programlisting role="php">
|
@@ -174,6 +180,48 @@ echo Foo::{$name}, PHP_EOL; // bar
|
174 | 180 | variable.
|
175 | 181 | </para>
|
176 | 182 | </note>
|
| 183 | + <example> |
| 184 | + <title>Assigning types to class constants, as of PHP 8.3.0</title> |
| 185 | + <programlisting role="php"> |
| 186 | +<![CDATA[ |
| 187 | +<?php |
| 188 | +
|
| 189 | +class MyClass { |
| 190 | + public const bool MY_BOOL = true; |
| 191 | + public const int MY_INT = 1; |
| 192 | + public const float MY_FLOAT = 1.01; |
| 193 | + public const string MY_STRING = 'one'; |
| 194 | + public const array MY_ARRAY = [self::MY_BOOL, self::MY_INT, self::MY_FLOAT, self::MY_STRING]; |
| 195 | +} |
| 196 | +
|
| 197 | +var_dump(MyClass::MY_BOOL); |
| 198 | +var_dump(MyClass::MY_INT); |
| 199 | +var_dump(MyClass::MY_FLOAT); |
| 200 | +var_dump(MyClass::MY_STRING); |
| 201 | +var_dump(MyClass::MY_ARRAY); |
| 202 | +?> |
| 203 | +]]> |
| 204 | + </programlisting> |
| 205 | + &example.outputs.83; |
| 206 | + <screen> |
| 207 | +<![CDATA[ |
| 208 | +bool(true) |
| 209 | +int(1) |
| 210 | +float(1.01) |
| 211 | +string(3) "one" |
| 212 | +array(4) { |
| 213 | + [0]=> |
| 214 | + bool(true) |
| 215 | + [1]=> |
| 216 | + int(1) |
| 217 | + [2]=> |
| 218 | + float(1.01) |
| 219 | + [3]=> |
| 220 | + string(3) "one" |
| 221 | +} |
| 222 | + ]]> |
| 223 | + </screen> |
| 224 | + </example> |
177 | 225 | </sect1>
|
178 | 226 | <!-- Keep this comment at the end of the file
|
179 | 227 | Local variables:
|
|
0 commit comments