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?
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, becauseecho(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.
http://php.net/manual/en/class.reflectionclass.php and print_r( );
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.