-
Notifications
You must be signed in to change notification settings - Fork 0
/
arrays.php
85 lines (64 loc) · 2.46 KB
/
arrays.php
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
<?php
declare(strict_types=1);
class Person {}
function takesInt(int $value): void {}
function takesString(string $value): void {}
function takesArrayKey(string|int $value): void {}
function takesPerson(Person $person): void {}
function takesAnyArray(array $array): void {}
/** @param Person[] $array */
function takesShortSyntaxArray(array $array): void {}
/** @param array<Person> $array */
function takesValueTypeOnlyArray(array $array): void {}
/** @param array<int,Person> $array */
function takesIntKeyAndValueArray(array $array): void {}
/** @param array<string,Person> $array */
function takesStringKeyAndValueArray(array $array): void {}
/** @return Person[] */
function providesShortSyntax()
{
return [new Person()];
}
$shortSyntaxArray = providesShortSyntax();
takesAnyArray($shortSyntaxArray); // OK
takesValueTypeOnlyArray($shortSyntaxArray); // OK
takesIntKeyAndValueArray($shortSyntaxArray); // ERROR: Array key is not guaranteed int
takesStringKeyAndValueArray($shortSyntaxArray); // ERROR: Array key is not guaranteed string
foreach($shortSyntaxArray as $key => $value) {
takesPerson($value); // OK
takesArrayKey($key); // OK
takesString($key); // ERROR: Array key is not guaranteed int
takesInt($key); // ERROR: Array key is not guaranteed string
}
/** @return array<Person> */
function providesValueOnly()
{
return [new Person()];
}
$valueOnlyArray = providesValueOnly();
takesAnyArray($valueOnlyArray); // OK
takesValueTypeOnlyArray($valueOnlyArray); // OK
takesIntKeyAndValueArray($valueOnlyArray); // ERROR: Array key is not guaranteed int
takesStringKeyAndValueArray($valueOnlyArray); // ERROR: Array key is not guaranteed string
foreach($valueOnlyArray as $key => $value) {
takesPerson($value); // OK
takesArrayKey($key); // OK
takesString($key); // ERROR: Array key is not guaranteed int
takesInt($key); // ERROR: Array key is not guaranteed string
}
/** @return array<int, Person> */
function providesKeyAndValue()
{
return [new Person()];
}
$keyAndValueArray = providesKeyAndValue();
takesAnyArray($keyAndValueArray); // OK
takesValueTypeOnlyArray($keyAndValueArray); // OK
takesIntKeyAndValueArray($keyAndValueArray); // OK
takesStringKeyAndValueArray($keyAndValueArray); // ERROR: Expects array<string,Person> given array<int,Person>
foreach($keyAndValueArray as $key => $value) {
takesPerson($value); // OK
takesArrayKey($key); // OK
takesString($key); // ERROR: expects string, int given
takesInt($key); // OK
}