Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "echo" a class?

Tags:

php

tostring

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?

like image 502
Andrew Avatar asked Oct 24 '09 23:10

Andrew


People also ask

How to echo class in php?

The echo() function outputs one or more strings. Note: The echo() function is not actually a function, so you are not required to use parentheses with it. However, if you want to pass more than one parameter to echo(), using parentheses will generate a parse error.


1 Answers

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;
?>
like image 71
David Snabel-Caunt Avatar answered Oct 10 '22 15:10

David Snabel-Caunt