xref: /PHP-8.2/tests/classes/tostring_004.phpt (revision fbe30592)
1--TEST--
2Object to string conversion: error cases and behaviour variations.
3--FILE--
4<?php
5function test_error_handler($err_no, $err_msg, $filename, $linenum) {
6        echo "Error: $err_no - $err_msg\n";
7}
8set_error_handler('test_error_handler');
9error_reporting(8191);
10
11
12echo "Object with no __toString():\n";
13$obj = new stdClass;
14echo "Try 1:\n";
15try {
16    printf($obj);
17} catch (Error $e) {
18    echo $e->getMessage(), "\n";
19}
20printf("\n");
21
22echo "\nTry 2:\n";
23try {
24    printf($obj . "\n");
25} catch (Error $e) {
26    echo $e->getMessage(), "\n";
27}
28
29echo "\n\nObject with bad __toString():\n";
30class badToString {
31    function __toString() {
32        return [];
33    }
34}
35
36$obj = new badToString;
37echo "Try 1:\n";
38try {
39    printf($obj);
40} catch (Error $e) {
41    echo $e->getMessage(), "\n";
42}
43printf("\n");
44
45echo "\nTry 2:\n";
46try {
47    printf($obj . "\n");
48} catch (Error $e) {
49    echo $e->getMessage(), "\n";
50}
51
52?>
53--EXPECT--
54Object with no __toString():
55Try 1:
56printf(): Argument #1 ($format) must be of type string, stdClass given
57
58
59Try 2:
60Object of class stdClass could not be converted to string
61
62
63Object with bad __toString():
64Try 1:
65badToString::__toString(): Return value must be of type string, array returned
66
67
68Try 2:
69badToString::__toString(): Return value must be of type string, array returned
70