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 []; 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"; 59try { 60 echo $ar[$o]; 61} catch (Error $e) { 62 echo $e->getMessage(), "\n"; 63} 64 65echo "====test8====\n"; 66var_dump(trim($o)); 67var_dump(trim((string)$o)); 68 69echo "====test9====\n"; 70echo sprintf("%s", $o); 71 72echo "====test10====\n"; 73$o = new test3; 74var_dump($o); 75try { 76 echo $o; 77} catch (Error $e) { 78 echo $e->getMessage(), "\n"; 79} 80 81?> 82====DONE==== 83--EXPECT-- 84====test1==== 85test1 Object 86( 87) 88Object of class test1 could not be converted to string 89object(test1)#1 (0) { 90} 91====test2==== 92test2 Object 93( 94) 95test2::__toString() 96Converted 97object(test2)#3 (0) { 98} 99====test3==== 100test2::__toString() 101Converted 102====test4==== 103test2::__toString() 104string:Converted 105====test5==== 106test2::__toString() 1071Converted 1081test2::__toString() 109Converted 110====test6==== 111test2::__toString() 112test2::__toString() 113Converted 114Converted 115test2::__toString() 116Converted 117test2::__toString() 118Converted 119====test7==== 120test2::__toString() 121Cannot access offset of type test2 on array 122====test8==== 123test2::__toString() 124string(9) "Converted" 125test2::__toString() 126string(9) "Converted" 127====test9==== 128test2::__toString() 129Converted 130====test10==== 131object(test3)#2 (0) { 132} 133test3::__toString() 134test3::__toString(): Return value must be of type string, array returned 135====DONE==== 136