Private Properties Exposed

For our Components project we are ofcourse writing unit tests (with PHPUnit ). Sometimes you would want to test whether a private property contains the correct data, and of course with the normal visibility rules you can't access those from your unit test. There is an interesting trick for this, which I'll share here:

<?php
class foo {
    private $bar = 42;
}
$obj = new foo;
$propname="\0foo\0bar";
$a = (array) $obj;
echo $a[$propname];
?>


Shortlink

This article has a short URL available: https://drck.me/ppe-46g

Comments

$f->{"0Foo0id"} (for private members) and $f->{"0*0name"} (for protected ones) used to work. Too bad someone added a "Cannot access property started with '0'" fatal error to the Zend Engine in the meantime, making necessary the array-cast hack presented here...

I'd rather have ReflectionProperty->setAccessible(TRUE) like (insert other programming language here):)

Add Comment

Name:
Email:

Will not be posted. Please leave empty instead of filling in garbage though!
Comment:

Please follow the reStructured Text format. Do not use the comment form to report issues in software, use the relevant issue tracker. I will not answer them here.


All comments are moderated
Become a Patron!
Mastodon
GitHub
LinkedIn
RSS Feed
Flickr
YouTube
Vimeo
Email

My Amazon wishlist can be found here.

Life Line