Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

PHP Features

Last updated: 10 September 2026