tags:

views:

108

answers:

3

This is probably really easy but I can't seem to figure out how to print/echo a class so I can find out some details about it.

I know this doesn't work, but this is what I'm trying to do:

<?php echo $class; ?>

What is the correct way to achieve something like this?

+7  A: 

You could try adding a toString method to your class. You can then echo some useful information, or call a render method to generate HTML or something!

The __toString method is called when you do something like the following:

echo $class;

or

$str = (string)$class;

The example linked is as follows:

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo) {
        $this->foo = $foo;
    }

    public function __toString() {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>
David Caunt
as you were first to answer, you've got 2 :)
Juraj Blahunka
+6  A: 

If you just want to print the contents of the class for debugging purposes, use print_r or var_dump.

James McNellis
+1 for speed :-)
Luc M
Do I get +1 for speed?
David Caunt
so fast the answer I was going to accept had already been deleted for being a duplicate
Andrew
+3  A: 

Use var_dump on an instance of your class.

<?php
$my_class = new SomeClass();
var_dump( $my_class );
?>
Luc M
-1 for slowness .. jk
Greg Dean