4

Possible Duplicate:
PHP ToString() equivalent
How to convert a PHP object to a string?

I'm looking for a function that can take any kind of variable (primitive, object, array, ...) and convert it to a string, for debugging purposes.

This is the best question I could find about converting objects to strings. Its answers don't seem to contain a general purpose solution that can handles all kinds of objects. I've tried (string)x, strval(x) and serialize(x), and also json_encode(x) from this answer.

(string)x and strval(x) cause Object of class Foo could not be converted to string. json_encode(x) returns an empty string for me. serialize() does work, but its output is not only textual (it contains weird "NULLs" and is a bit hard to read.

I tried search Stack Overflow for Object of class Foo could not be converted to string, but found a ton of specific question that got zero upvotes and no general solutions.

The question, again - how to pretty print / convert any php value into a string in php?

Community
  • 1
  • 1
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • I got my answer - it is actually the fifth answer on this question - http://stackoverflow.com/a/3559247/11236 - voting to close this one. – ripper234 Jan 03 '13 at 16:21

3 Answers3

4

I usually go for print_r, works great for me so far.

PHP manual: http://php.net/manual/en/function.print-r.php

print_r — Prints human-readable information about a variable

Bono
  • 4,757
  • 6
  • 48
  • 77
  • 1
    I thought this answer was useless because `print_r` just didn't work for me, but then I realized print_r ***prints by default***, and does't return the correct value. Use `print_r(foo, true)` to return the value! – ripper234 Jan 03 '13 at 16:16
3

I prefer:

print_r($object, true);

This does print a nice view of the object into a string.

Marko
  • 514
  • 1
  • 4
  • 16
1

If this is just for debugging the easiest solution is to use print_r or var_dump. In case you display this in a HTML document you can wrap a <pre> tag around to have this formatted well readable.

<pre>    
<?php print_r( $object ); ?>
</pre>

Example output of

$object = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

print_r( $object );

print_r uses \n and \t to format:

mysqli Object
(
    [affected_rows] => 0
    [client_info] => 5.1.62
    [client_version] => 50162
    [connect_errno] => 0
    [connect_error] =>
    [errno] => 0
    [error] =>
    [error_list] => Array
        (
        )

    [field_count] => 0
    [host_info] => 127.0.0.1 via TCP/IP
    [info] =>
    [insert_id] => 0
    [server_info] => 5.5.20
    [server_version] => 50520
    [stat] => Uptime: 11556798  Threads: 2  Questions: 1351931648  Slow queries: 421  Opens: 225532  Flush tables: 1  Open tables: 1017  Queries per second avg: 116.981
    [sqlstate] => 00000
    [protocol_version] => 10
    [thread_id] => 171160
    [warning_count] => 0
)
Michel Feldheim
  • 17,625
  • 5
  • 60
  • 77