How to “echo” a class?

谁说胖子不能爱 提交于 2019-12-19 12:49:57

问题


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?


回答1:


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




回答2:


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;
?>



回答3:


Use var_dump on an instance of your class.

<?php
$my_class = new SomeClass();
var_dump( $my_class );
?>



回答4:


To get more detailed info out of your class (if you want to know what's available to a child class for example), you can add a debug() method.

Here's an example class with such a method that I use that prints out the methods, default vars, and instance vars in a nice structured way:

<?php
class TestClass{
    private $privateVar = 'Default private';
    protected $protectedVar = 'Default protected';
    public $publicVar = 'Default public';

    public function __construct(){
        $this->privateVar = 'parent instance';
    }
    public function test(){}
    /**
     * Prints out detailed info of the class and instance.
     */
    public function debug(){
        $class = __CLASS__;
        echo "<pre>$class Methods:\n";
        var_dump(get_class_methods($class));
        echo "\n\n$class Default Vars:\n";
        var_dump(get_class_vars($class));
        echo "\n\n$class Current Vars:\n";
        var_dump($this);
        echo "</pre>";
    }
}

class TestClassChild extends TestClass{
    public function __construct(){
        $this->privateVar = 'child instance';
    }
}

$test = new TestClass();
$test2 = new TestClassChild();

$test->debug();
$test2->debug();



回答5:


You can use Symfony VarDumper Component http://symfony.com/doc/current/components/var_dumper/introduction.html:

Install it via Composer:

composer require symfony/var-dumper 

Usage:

require __DIR__.'/vendor/autoload.php';

// create a variable, which could be anything!
$someVar = ...;

dump($someVar);


来源:https://stackoverflow.com/questions/1619483/how-to-echo-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!