Cast Private To Array
By Paul Shryock
<?php
class MyClass {
private $hi = 'Hi';
protected $hello = 'Hello';
public $goodday = 'Goodday';
}
$thing = new MyClass();
print json_encode($thing); // {"goodday":"Goodday"}
print json_encode((array) $thing);
// {" MyClass hi":"Hi"," * hello":"Hello","goodday":"Goodday"}
Today I learned that PHP exposes private properties when an object is cast to an array. 🤦.
See Also
- Original Toot
- Casting private properties [Try me]
PHP Features
Last updated: 10 September 2026