开发者

Display data from private/protected properties and methods

I am executing print_r() on an object. Which displays a nicely formatted output. However, I want to control the output. I want to be able to format and add titles/headers to certain sections of the output. print_r() is awesome but I cannot figure out how to access different lines within the output. I attempted to do something like this:

echo '<h1>ERRORS</h1>';
echo '<h3>Properties</h3>';
print_r(Exception::$message);

However, $message is set as a protected property so I ended up getting this error:

Fatal error: Cannot access protected property Exception::$message...

I don't want to access $message in order to modify it. I just want to display it like print_r() does...but nicely formatted my way. Perhaps I'm not fully understanding what 'access' rea开发者_如何学Clly means.

I also tried something like this also:

$lines = explode("\n", print_r(Exception::$message, true));
foreach ($lines as $line) {
    echo $line;
}

...but I get the same error

Fatal error: Cannot access protected property Exception::$message...

Is there a way to do this? Or is there a way to properly access the contents of print_r()?


print_r() as well as var_dump() are just for debugging, so it was never intended, that it should look nice.

However, if you want to output an object more "pretty", you need to build it yourself. Have a look at the Reflection-API.

You should NEVER leave this kind of (debug) output on a production server!


print_r's output is a plain piece of text, and you have no control over it - it's just a dump of some variable or object's contents. If you want formatting, you'll have to roll your own version of print_r, especially if you want to deal with protected/private parts of an object. Since they're protected, you can't access them from outside the object.

e.g.

 $x = new MyObj;
 print_r($x::some_protected_variable);

would not work, since you're not "inside" the object while accessing that variable. You'd have to add a 'dump' method to the object:

 $x = new MyObj;
 $x->dump('some_protected_variable');

and have the dump function do the accessing/dumping.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜