简体   繁体   中英

How can I print the items of a class in PHP?

I have this class:

class MyClass {
    public $dummy = array('foo', 'bar', 'baz', 'qux');
    public $progr = array('HTML', 'CSS', 'JS', 'PHP');
}

I'm trying to print that out: print_r(MyClass) , but it outputs MyClass and nothing else. I get similiar things with echo , print , var_dump and var_export . It seems that they treat MyClass as a string, because echo(test) outputs test .

So, how can I list the items of a class?

Use ReflectionClass on an instance of your class, and optionally use ReflectionProperty to get the values of the properties as in your instance:

$rc = new ReflectionClass(new MyClass());

foreach ($rc->getProperties() as $property) {
    printf('%s = %s', $property->getName(), print_r($property->getValue(), true));
}

On second thought, if you just want to get the values of an object's properties then mingos' answer using print_r(new MyClass()); works too.

Another thing,

It seems that they treat MyClass as a string, because echo(test) outputs test .

This is normal: PHP first treats them as constant names, but if it can't find constants defined with those names, then it treats them as unquoted string literals.

Have you instantiated it?

What does this output:

$m = new MyClass();
print_r($m);

Sometimes it can be helpful to implement the class's __toString magic method as well. In brief, __toString allows you to specify exactly how an object should behave when it is echoed. For more information, please see the following:

http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring

I like to use __toString as a debugging tool, though I'm sure the true potential of the method is significantly more profound :)

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM