开发者

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.

S开发者_如何学Co, how can I list the items of a class?


Have you instantiated it?

What does this output:

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


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.


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.


http://php.net/manual/en/class.reflectionclass.php and print_r( );

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜