Is it possible to override print_r's behaviour on an ArrayIterator object in PHP?
I've got a PHP class which extends ArrayIterator, and has all the necessary methods implemented so that it behaves like an array.
This works fine for things like foreach
loops, but calling print_r
on it still prints out the object's variables, rather than printing it as it would an array.
Is there some way of overriding this behaviour so that calling print_r
(and I g开发者_C百科uess var_dump
) will print custom output for this object?
No, because it is designed to give information about the variable (i.e. it is used for debugging) and not just to give some string representation of it.
You can overwrite __toString
though and use echo
.
Since PHP 5.6 the magic method __debuginfo
has been added, if you implement it you should be able to overrite the var_dump
and print_r
behavoir.
seh here: http://php.net/manual/language.oop5.magic.php#object.debuginfo
And why don't you use the getArrayCopy method?
ie.
print_r($yourIterator->getArrayCopy());
If don't think it is, unless using PHP Runkit
but I wouldn't recommend this as it would change the expected behavior that your user will expect.
another good way would be to make your own function (e.g.: my_print_r() { /* some code */ }
or use the __toString()
magical method.
What is it for ?
精彩评论