summaryrefslogtreecommitdiff
path: root/Zend/tests/attributes/005_objects.phpt
blob: 62b14181efd2e29681bfcd24667aa5b6f40c9122 (plain)
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
--TEST--
Attributes can be converted into objects.
--FILE--
<?php

#[Attribute(Attribute::TARGET_FUNCTION)]
class A1
{
    public string $name;
    public int $ttl;

    public function __construct(string $name, int $ttl = 50)
    {
        $this->name = $name;
        $this->ttl = $ttl;
    }
}

$ref = new \ReflectionFunction(#[A1('test')] function () { });

foreach ($ref->getAttributes() as $attr) {
    $obj = $attr->newInstance();

    var_dump(get_class($obj), $obj->name, $obj->ttl);
}

echo "\n";

$ref = new \ReflectionFunction(#[A1] function () { });

try {
    $ref->getAttributes()[0]->newInstance();
} catch (\ArgumentCountError $e) {
    var_dump('ERROR 1', $e->getMessage());
}

echo "\n";

$ref = new \ReflectionFunction(#[A1([])] function () { });

try {
    $ref->getAttributes()[0]->newInstance();
} catch (\TypeError $e) {
    var_dump('ERROR 2', $e->getMessage());
}

echo "\n";

$ref = new \ReflectionFunction(#[A2] function () { });

try {
    $ref->getAttributes()[0]->newInstance();
} catch (\Error $e) {
    var_dump('ERROR 3', $e->getMessage());
}

echo "\n";

#[Attribute]
class A3
{
    private function __construct() { }
}

$ref = new \ReflectionFunction(#[A3] function () { });

try {
    $ref->getAttributes()[0]->newInstance();
} catch (\Error $e) {
    var_dump('ERROR 4', $e->getMessage());
}

echo "\n";

#[Attribute]
class A4 { }

$ref = new \ReflectionFunction(#[A4(1)] function () { });

try {
    $ref->getAttributes()[0]->newInstance();
} catch (\Error $e) {
    var_dump('ERROR 5', $e->getMessage());
}

echo "\n";

class A5 { }

$ref = new \ReflectionFunction(#[A5] function () { });

try {
    $ref->getAttributes()[0]->newInstance();
} catch (\Error $e) {
    var_dump('ERROR 6', $e->getMessage());
}

?>
--EXPECT--
string(2) "A1"
string(4) "test"
int(50)

string(7) "ERROR 1"
string(81) "Too few arguments to function A1::__construct(), 0 passed and at least 1 expected"

string(7) "ERROR 2"
string(74) "A1::__construct(): Argument #1 ($name) must be of type string, array given"

string(7) "ERROR 3"
string(30) "Attribute class "A2" not found"

string(7) "ERROR 4"
string(48) "Attribute constructor of class A3 must be public"

string(7) "ERROR 5"
string(69) "Attribute class A4 does not have a constructor, cannot pass arguments"

string(7) "ERROR 6"
string(55) "Attempting to use non-attribute class "A5" as attribute"