xref: /PHP-7.4/tests/classes/tostring_001.phpt (revision a31f4642)
1--TEST--
2ZE2 __toString()
3--FILE--
4<?php
5
6class test1
7{
8}
9
10class test2
11{
12    function __toString()
13    {
14    	echo __METHOD__ . "()\n";
15        return "Converted\n";
16    }
17}
18
19class test3
20{
21    function __toString()
22    {
23    	echo __METHOD__ . "()\n";
24        return 42;
25    }
26}
27echo "====test1====\n";
28$o = new test1;
29print_r($o);
30try {
31    var_dump((string)$o);
32} catch (Error $e) {
33    echo $e->getMessage(), "\n";
34}
35var_dump($o);
36
37echo "====test2====\n";
38$o = new test2;
39print_r($o);
40print $o;
41var_dump($o);
42echo "====test3====\n";
43echo $o;
44
45echo "====test4====\n";
46echo "string:".$o;
47
48echo "====test5====\n";
49echo 1 . $o;
50echo 1 , $o;
51
52echo "====test6====\n";
53echo $o . $o;
54echo $o , $o;
55
56echo "====test7====\n";
57$ar = array();
58$ar[$o->__toString()] = "ERROR";
59echo $ar[$o];
60
61echo "====test8====\n";
62var_dump(trim($o));
63var_dump(trim((string)$o));
64
65echo "====test9====\n";
66echo sprintf("%s", $o);
67
68echo "====test10====\n";
69$o = new test3;
70var_dump($o);
71try {
72    echo $o;
73} catch (Error $e) {
74    echo $e->getMessage(), "\n";
75}
76
77?>
78====DONE====
79--EXPECTF--
80====test1====
81test1 Object
82(
83)
84Object of class test1 could not be converted to string
85object(test1)#1 (0) {
86}
87====test2====
88test2 Object
89(
90)
91test2::__toString()
92Converted
93object(test2)#3 (0) {
94}
95====test3====
96test2::__toString()
97Converted
98====test4====
99test2::__toString()
100string:Converted
101====test5====
102test2::__toString()
1031Converted
1041test2::__toString()
105Converted
106====test6====
107test2::__toString()
108test2::__toString()
109Converted
110Converted
111test2::__toString()
112Converted
113test2::__toString()
114Converted
115====test7====
116test2::__toString()
117
118Warning: Illegal offset type in %s on line %d
119====test8====
120test2::__toString()
121string(9) "Converted"
122test2::__toString()
123string(9) "Converted"
124====test9====
125test2::__toString()
126Converted
127====test10====
128object(test3)#1 (0) {
129}
130test3::__toString()
131Method test3::__toString() must return a string value
132====DONE====
133