You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Since PHP 8.1, you can use an "intersection type" (also known as "pure") that enforce that a given value belong to every types. For example this param needs to implement both __Stringable__ and __Countable__ interfaces:
270
+
271
+
```php
272
+
function myFunction(Stringable&Countable $param): Stringable&Countable
273
+
{
274
+
return $param;
275
+
}
276
+
Class Foo
277
+
{
278
+
public function __toString() {
279
+
return "something";
280
+
}
281
+
}
282
+
myFunction(new Foo());
283
+
// TypeError: myFunction(): Argument #1 ($param) must be of type Stringable&Countable, Foo given
284
+
```
285
+
286
+
It also works with class property:
287
+
288
+
```php
289
+
Class Foo
290
+
{
291
+
public Stringable&Countable $bar;
292
+
}
293
+
```
294
+
295
+
Intersection type only supports class and interfaces. Scalar types (string, int, array, null, mixed, etc) are not allowed:
296
+
297
+
```php
298
+
function myFunction(string&Countable $param)
299
+
{
300
+
return $param;
301
+
}
302
+
// PHP Fatal error: Type string cannot be part of an intersection type
303
+
```
304
+
305
+
##### External resource
306
+
307
+
-[Intersection types on PHP.Watch](https://php.watch/versions/8.1/intersection-types)
0 commit comments