Use get_object_vars($object). It returns an associative array of the properties visible where you call it: only public ones from outside the class, all of them from inside. It converts one level; for nested objects use json_decode(json_encode($object), true) or a small recursive function. The other way round, (object) $array gives a stdClass object.
PHP has several ways to turn an object into an array, and they differ on two things: which properties you get (public only, or private and protected too) and whether nested objects are converted. get_object_vars respects visibility, the (array) cast includes everything but hides prefixes in the keys, and a JSON round trip goes all the way down at the cost of types. The sections below cover each one, a recursive function that handles dates and enums, what stdClass is and why your own classes no longer accept new properties, and converting an array back into an object, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1get_object_vars()Recommended
get_object_vars returns the object's properties as a name => value array with clean string keys. It is scope-aware: called from outside the class it returns only public properties, and called inside a method it also returns protected and private ones. That makes return get_object_vars($this); the shortest toArray() method you can write. A foreach over an object walks the same set of visible properties, so you often don't need an array at all.
<?php class User { public int $id = 1; public string $name = 'Ada'; protected string $role = 'admin'; private string $password = 'secret'; public function toArray(): array { // Inside the class, every property is in scope return get_object_vars($this); } } $user = new User(); // From outside, only public properties come back print_r(get_object_vars($user)); print_r($user->toArray()); // foreach over an object walks the same visible properties foreach ($user as $key => $value) { echo $key, ' = ', var_export($value, true), "\n"; }
Output
Called from the outside, the array has only [id] and [name]. The same function inside toArray() adds [role] => admin and [password] => secret, so decide what a public toArray() should expose before you return everything. The foreach prints id = 1 and name = 'Ada': public properties only, because the loop runs outside the class. Nested objects are not converted; they stay objects inside the array (section 3).
2The (array) cast and its hidden keys
The top Stack Overflow answer is (array) $object, and for a stdClass or a class with only public properties it gives the same result as get_object_vars. The difference shows with non-public properties: the cast always includes them, whatever the scope, and marks them in the key with NUL bytes. A protected property becomes "\0*\0role" and a private one becomes "\0User\0password", with the class name in the middle. You can't see those bytes when you print the array, which is why $array['role'] mysteriously fails. The example makes them visible.
<?php class User { public string $name = 'Ada'; protected string $role = 'admin'; private string $password = 'secret'; } $array = (array) new User(); // Private and protected keys carry NUL bytes; print them as \0 foreach ($array as $key => $value) { $shown = str_replace("\0", '\0', $key); printf("%-16s %2d bytes %s\n", $shown, strlen($key), $value); } // So a plain key lookup misses them var_dump(isset($array['role']), isset($array["\0*\0role"])); // json_encode() keeps the NUL bytes too echo json_encode($array), "\n"; // Strip the prefix to get plain names $clean = []; foreach ($array as $key => $value) { $clean[preg_replace('/^\0[^\0]+\0/', '', $key)] = $value; } print_r($clean);
Output
role is 4 letters but its key is 7 bytes, and the private password key is 14 bytes. isset($array['role']) is bool(false) while the full "\0*\0role" key is bool(true), and json_encode writes the bytes out as \u0000. The preg_replace loop strips the prefixes and gives plain names. get_mangled_object_vars() (PHP 7.4) returns the same mangled array as the cast. Use the cast for stdClass and public-only objects; when you want private properties, a toArray() method with get_object_vars($this) is cleaner than unpicking keys.
3Nested objects: json_decode(json_encode())
get_object_vars and the cast convert one level: a property that holds another object is still an object in the result. The popular one-liner for a full conversion is to encode the object to JSON and decode it with true as the second argument, which turns every JSON object into an associative array. It is short, but it works through JSON's rules: only public properties are encoded, a float with no fraction comes back as an int, and objects such as DateTimeImmutable come back as whatever json_encode made of them.
<?php class Address { public function __construct( public string $city, public string $zip, ) {} } class Order { public function __construct( public int $id, public float $total, public Address $shipTo, public DateTimeImmutable $placed, private string $note = 'internal', ) {} } $order = new Order( 7, 20.0, new Address('Lisbon', '1100'), new DateTimeImmutable('2026-12-01 09:30'), ); // get_object_vars() goes one level deep: shipTo is still an object echo get_debug_type(get_object_vars($order)['shipTo']), "\n"; // Encode to JSON, decode with true: arrays all the way down $array = json_decode(json_encode($order, JSON_THROW_ON_ERROR), true); print_r($array); // 20.0 comes back as int 20 unless you keep the zero fraction var_dump($array['total']); $json = json_encode($order, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION); var_dump(json_decode($json, true)['total']);
Output
The first line, Address, shows that get_object_vars left the nested object alone. After the round trip shipTo is an array, the private note is gone, and placed became [date], [timezone_type] and [timezone], which is not a format you want to pass around. total was 20.0 but comes back as int(20); the JSON_PRESERVE_ZERO_FRACTION flag keeps it float(20). JSON_THROW_ON_ERROR makes a failed encode (invalid UTF-8, NAN) throw instead of returning false. For plain data objects the round trip is fine; for anything with dates, enums or private state, use the function in the next section.
4Nested objects: a recursive function
A recursive function converts every level without going through a string and lets you decide what each kind of value becomes. The version below turns dates into ISO 8601 strings and backed enums into their value, converts any other object with get_object_vars, maps over arrays so lists of objects work, and leaves scalars alone, so 20.0 stays a float. Enums and dates are objects too, which is why their cases come before is_object in the match.
<?php enum Status: string { case Paid = 'paid'; case Shipped = 'shipped'; } class Item { public function __construct( public string $sku, public int $qty, ) {} } class Order { public function __construct( public int $id, public float $total, public Status $status, public DateTimeImmutable $placed, public array $items, ) {} } // Walk the value: objects and arrays recurse, the rest is kept as is function toArray(mixed $value): mixed { return match (true) { $value instanceof DateTimeInterface => $value->format(DATE_ATOM), $value instanceof BackedEnum => $value->value, is_object($value) => toArray(get_object_vars($value)), is_array($value) => array_map(toArray(...), $value), default => $value, }; } $order = new Order( 7, 20.0, Status::Paid, new DateTimeImmutable('2026-12-01 09:30'), [new Item('A-1', 2), new Item('B-7', 1)], ); $array = toArray($order); print_r($array); var_dump($array['total']); // Without the DateTimeInterface case you would get an empty array var_dump(get_object_vars($order->placed));
Output
Every level is an array now: [status] => paid, [placed] => 2026-12-01T09:30:00+00:00, and [items] is a list of two arrays. var_dump confirms total is still float(20); print_r just prints floats without the .0. The last line shows why dates need their own case: get_object_vars on a DateTimeImmutable returns array(0). Because the function sits outside the classes, it sees public properties only; to include private ones, give each class a toArray() that calls get_object_vars($this) and recurse from there. The toArray(...) callable syntax needs PHP 8.1; on older versions pass 'toArray' as a string.
5What stdClass is, and dynamic properties
stdClass is PHP's built-in empty class: no properties, no methods, and you can add any property to it at run time. You get one from new stdClass(), from casting an array with (object), and from json_decode, which returns stdClass objects unless you pass true (see parsing JSON into an array). It is not a base class of other objects, just a plain container. Your own classes are different: since PHP 8.2, assigning a property the class doesn't declare raises a deprecation, unless the class carries the #[\AllowDynamicProperties] attribute. This example triggers that deprecation on purpose.
<?php // stdClass: an empty object that takes any property $point = new stdClass(); $point->x = 3; $point->y = 4; echo get_class($point), ' ', $point->x + $point->y, "\n"; // json_decode() returns stdClass objects by default $config = json_decode('{"debug":true,"db":{"host":"localhost"}}'); echo get_class($config->db), ' ', $config->db->host, "\n"; // Loop over its properties like an array foreach ($point as $name => $value) { echo "$name = $value\n"; } var_dump(isset($point->z), property_exists($point, 'x')); // Your own classes: dynamic properties are deprecated since PHP 8.2 class Product { public string $name = 'Lamp'; } $product = new Product(); $product->price = 25; // Deprecated: Creation of dynamic property echo $product->price, "\n"; #[\AllowDynamicProperties] class LegacyProduct { public string $name = 'Desk'; } $legacy = new LegacyProduct(); $legacy->price = 120; // allowed, no notice echo $legacy->price, "\n";
Output
The stdClass lines run cleanly: stdClass 7, the nested db object from the JSON, and a foreach that prints x = 3 and y = 4. The Product assignment still works and prints 25, but stderr shows Deprecated: Creation of dynamic property Product::$price is deprecated, and PHP 9 is planned to make it an error. Fix it by declaring the property; use #[\AllowDynamicProperties] only for old code you can't change yet. LegacyProduct prints 120 with no notice, and stdClass never needs the attribute.
6Convert an array to an object
(object) $array turns an associative array into a stdClass whose properties are the keys. Like the cast in the other direction it is one level deep: a nested array stays an array. For a deep conversion, encode to JSON and decode without true. Keys that are not valid property names, such as first-name or a number, still work through the $obj->{'first-name'} syntax. When you want a real class rather than a stdClass, spread the array into the constructor as named arguments (PHP 8.1 and later).
<?php
$array = [
'name' => 'Ada',
'tags' => ['admin', 'ops'],
'address' => ['city' => 'Lisbon'],
];
// (object) converts one level; nested arrays stay arrays
$obj = (object) $array;
echo get_class($obj), ' ', $obj->name, "\n";
echo get_debug_type($obj->address), ' ', $obj->address['city'], "\n";
// JSON round trip converts every level
$deep = json_decode(json_encode($array, JSON_THROW_ON_ERROR));
echo get_debug_type($deep->address), ' ', $deep->address->city, "\n";
echo get_debug_type($deep->tags), ' ', $deep->tags[0], "\n";
// Keys that are not valid names need braces
$odd = (object) ['first-name' => 'Ada', 0 => 'zero'];
echo $odd->{'first-name'}, ' ', $odd->{'0'}, "\n";
var_dump(array_keys((array) $odd));
// Into your own class: spread the array as named arguments
final class User
{
public function __construct(
public string $name,
public string $role = 'user',
) {}
}
$user = new User(...['name' => 'Grace', 'role' => 'admin']);
echo get_class($user), ' ', $user->name, ' ', $user->role, "\n";
Output
After (object), name is a property but address is still an array. The JSON round trip makes address a stdClass, while tags, a list, stays an array, because a JSON array decodes to a PHP array. The numeric key 0 is read as $odd->{'0'} and casts back to the int key int(0). Spreading into new User(...$array) gives a typed object with defaults and checks; a key with no matching parameter throws Error: Unknown named parameter, so filter input arrays first.
7Which should you use?
| Method | Direction | Depth | Watch out for |
|---|---|---|---|
| get_object_vars($obj) | To array | One level | Sees only what is in scope; best default |
| (array) $obj | To array | One level | NUL-prefixed keys for private and protected |
| json_decode(json_encode($obj), true) | To array | All levels | Public only; 20.0 becomes 20; dates become arrays |
| Recursive toArray() | To array | All levels | You choose how dates and enums convert |
| (object) $array | To object | One level | Nested arrays stay arrays |
| json_decode(json_encode($array)) | To object | All levels | Lists stay arrays |
| new User(...$array) | To your class | One level | Unknown keys throw an Error |
Frequently asked questions
What is stdClass in PHP?
stdClass is the built-in generic class with no properties and no methods. You can add any property to it at run time, and you get one from new stdClass(), from (object) $array, and from json_decode() without true. It is not a parent class of other objects, so $user instanceof stdClass is false for your own classes.
How do I fix "Cannot use object of type stdClass as array"?
You have an object and used array syntax on it. Read the value with ->, as in $data->name instead of $data['name'], or get arrays in the first place with json_decode($json, true). For one level, get_object_vars($data) or (array) $data also works.
Why is a property missing from get_object_vars()?
Either it is not visible from where you call it (protected and private properties only appear when you call it inside the class), or it is a typed property that was never initialized. A public int $age; with no value is left out of both get_object_vars() and the (array) cast until you assign it.
How do I get private properties from outside the class?
Best: add a toArray() method that returns get_object_vars($this). Without changing the class, the (array) cast includes private and protected properties under keys like "\0User\0password" and "\0*\0role", which you can clean with preg_replace. Reflection also works: since PHP 8.1, ReflectionProperty::getValue() reads private properties without calling setAccessible().
How do I fix "Creation of dynamic property is deprecated"?
PHP 8.2 deprecated assigning undeclared properties, and the message reads Deprecated: Creation of dynamic property Product::$price is deprecated. Declare the property in the class. If you cannot yet, put #[\AllowDynamicProperties] on the class, or store the extra values in an array property or a stdClass, which still accepts any property.
What does (array) do with a value that is not an object?
A scalar becomes a one-element array, so (array) 'hello' gives [0 => 'hello'], (array) 5 gives [0 => 5], (array) null gives an empty array, and an array is returned unchanged. That is handy when a value may be one item or a list, but it only converts objects one level deep.