I did it in this way

class Book {
    private $_name;
    private $_price;

    public function toArray() {
        $vars = get_object_vars ( $this );
        $array = array ();
        foreach ( $vars as value ) {
            $array [ltrim ( $key, '_' )] = $value;
        }
        return $array;
    }
}

and when I want to convert a book object to an array I call the toArray() function

$book->toArray();
Answer from Sachindra on Stack Overflow
🌐
Coderwall
coderwall.com › p › 36h6qa › converting-php-objects-to-arrays-to-read-private-members
Converting PHP Objects to Arrays to read private members (Example)
August 15, 2019 - <?php class Foo { public $bar = 'barValue'; protected $baz = 'bazValue'; private $tab = 'tabValue'; } var_dump((array) new Foo()); ... While this may not make sense to many people, this is how actually PHP represents objects internally, and it is thought this way to avoid any collisions in object serialization.
🌐
PHPpot
phppot.com › php › php-object-to-array
PHP Object to Array Convert using JSON Decode - PHPpot
Then, the Student class instance is encoded to prepare object type data. The json_encode() function prepares the JSON object to supply it for decoding. The json_decode() converts the PHP object to array.
Discussions

PHP Convert object to array - Stack Overflow
When a object with private variables, has converted (cast) to an array in php the array element keys will be started with *_ . How to remove the "*_"s that exists at the beginning of array keys?... More on stackoverflow.com
🌐 stackoverflow.com
March 11, 2016
php - How do I convert an object to an array? - Stack Overflow
If your array contains some other encoding, let say Win1250, it will fail, as json_encode will fail (php 5.3) 2013-12-03T14:40:05.633Z+00:00 ... @Trix use json again json_decode(json_encode($array), FALSE);This also (recursively) converts all of your sub arrays into objects, 2017-01-20T12:... More on stackoverflow.com
🌐 stackoverflow.com
Convert a PHP object to an associative array - Stack Overflow
I'm integrating an API to my website which works with data stored in objects while my code is written using arrays. I'd like a quick-and-dirty function to convert an object to an array. More on stackoverflow.com
🌐 stackoverflow.com
How to get protected property of object in PHP - Stack Overflow
In my case, I'm using Laravel's ... in a protected property. Being asynchronous makes that assertion a little tricky to make without this. Thanks @drewish. 2018-04-19T14:29:12.987Z+00:00 ... Save this answer. ... Show activity on this post. Object can be typecasted into (associative) array and the protected ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
PHP
php.net › manual › en › function.get-object-vars.php
PHP: get_object_vars - Manual
You can still cast the object to an array to get all its members and see its visibility. Example: <?php class Potatoe { public $skin; protected $meat; private $roots; function __construct ( $s, $m, $r ) { $this->skin = $s; $this->meat = $m; $this->roots = $r; } } $Obj = new Potatoe ( 1, 2, 3 ); echo "<pre>\n"; echo "Using get_object_vars:\n"; $vars = get_object_vars ( $Obj ); print_r ( $vars ); echo "\n\nUsing array cast:\n"; $Arr = (array)$Obj; print_r ( $Arr ); ?> This will returns: Using get_object_vars: Array ( [skin] => 1 ) Using array cast: Array ( [skin] => 1 [ * meat] => 2 [ Potatoe roots] => 3 ) As you can see, you can obtain the visibility for each member from this cast.
🌐
GitHub
gist.github.com › artturik › b0cc6835dfb95b8e9d8d31408aaab8cc
Dump object to array; convert all object accessible and non-accessible variables to array (public, protected, private, static properties and constants) · GitHub
Dump object to array; convert all object accessible and non-accessible variables to array (public, protected, private, static properties and constants) - DumpObject.php
🌐
GitHub
ocramius.github.io › blog › fast-php-object-to-array-conversion
Fast PHP Object to Array conversion
Apparently, it is possible to cast objects to arrays like following: <?php class Foo { public $bar = 'barValue'; } $foo = new Foo(); $arrayFoo = (array) $foo; var_dump($arrayFoo); ... <?php class Foo { public $bar = 'barValue'; protected $baz = 'bazValue'; private $tab = 'tabValue'; } $foo = new Foo(); $arrayFoo = (array) $foo; var_dump($arrayFoo);
🌐
Techie Delight
techiedelight.com › home › java › convert an object to an array in php
Convert an object to an array in PHP | Techie Delight
July 7, 2026 - You can convert the object into a string containing the JSON representation with json_encode(), and then convert the JSON string into an associative array using the json_decode() function with its second parameter set to true.
Top answer
1 of 4
12

I did it in this way

class Book {
    private $_name;
    private $_price;

    public function toArray() {
        $vars = get_object_vars ( $this );
        $array = array ();
        foreach ( $vars as value ) {
            $array [ltrim ( $key, '_' )] = $value;
        }
        return $array;
    }
}

and when I want to convert a book object to an array I call the toArray() function

$book->toArray();
2 of 4
3

to do this properly you need to implement a toArray() method in your class. That way you can keep your properties protected and still have access to the array of properties.
There are many ways to accomplish this, here is one method useful if you pass the object data to the constructor as an array.

//pass an array to constructor
public function __construct(array $options = NULL) {
        //if we pass an array to the constructor
        if (is_array($options)) {
            //call setOptions() and pass the array
            $this->setOptions($options);
        }
    }

    public function setOptions(array $options) {
        //an array of getters and setters
        $methods = get_class_methods($this);
        //loop through the options array and call setters
        foreach ($options as value) {
            //here we build an array of values as we set properties.
            $this->_data[value;
            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }
        return $this;
    }

//just return the array we built in setOptions
public function toArray() {

        return $this->_data;
    }

you can also build an array using your getters and code to make the array look how you want. Also you can use __set() and __get() to make this work as well.

when all is said and done the goal would be to have something that works like:

//instantiate an object
$book = new Book(array($values);
//turn object into an array
$array = $book->toArray();
Top answer
1 of 11
396

Single-dimensional arrays

For converting single-dimension arrays, you can cast using (array) or there's get_object_vars, which Benoit mentioned in his answer.

// Cast to an array
$array = (array) $object;
// get_object_vars
$array = get_object_vars($object);

They work slightly different from each other. For example, get_object_vars will return an array with only publicly accessible properties unless it is called from within the scope of the object you're passing (ie in a member function of the object). (array), on the other hand, will cast to an array with all public, private and protected members intact on the array, though all public now, of course.

Multi-dimensional arrays

A somewhat dirty method is to use PHP >= 5.2's native JSON functions to encode to JSON and then decode back to an array. This will not include private and protected members, however, and is not suitable for objects that contain data that cannot be JSON encoded (such as binary data).

// The second parameter of json_decode forces parsing into an associative array
$array = json_decode(json_encode($object), true);

Alternatively, the following function will convert from an object to an array including private and protected members, taken from here and modified to use casting:

function objectToArray ($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('objectToArray', (array) $object);
}
2 of 11
138

You should look at get_object_vars , as your properties are declared private you should call this inside the class and return its results.

Be careful, for primitive data types like strings it will work great, but I don't know how it behaves with nested objects.

in your case you have to do something like;

<?php
   print_r(get_object_vars($response->response->docs));
?>
Find elsewhere
Top answer
1 of 16
1825

Just typecast it

$array = (array) $yourObject;

From Arrays:

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

Example: Simple Object

$object = new StdClass;
$object->foo = 1;
$object->bar = 2;

var_dump( (array) $object );

Output:

array(2) {
  'foo' => int(1)
  'bar' => int(2)
}

Example: Complex Object

class Foo
{
    private $foo;
    protected $bar;
    public $baz;

    public function __construct()
    {
        $this->foo = 1;
        $this->bar = 2;
        $this->baz = new StdClass;
    }
}

var_dump( (array) new Foo );

Output (with \0s edited in for clarity):

array(3) {
  '\0Foo\0foo' => int(1)
  '\0*\0bar' => int(2)
  'baz' => class stdClass#2 (0) {}
}

Output with var_export instead of var_dump:

array (
  '' . "\0" . 'Foo' . "\0" . 'foo' => 1,
  '' . "\0" . '*' . "\0" . 'bar' => 2,
  'baz' =>
  stdClass::__set_state(array(
  )),
)

To know more about php built-in class stdclass. You can read this documentation

Typecasting this way will not do deep casting of the object graph and you need to apply the null bytes (as explained in the manual quote) to access any non-public attributes. So this works best when casting StdClass objects or objects with only public properties. For quick and dirty (what you asked for) it's fine.

Also see this in-depth blog post:

  • Fast PHP Object to Array conversion
2 of 16
540

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:

$array = json_decode(json_encode($nested_object), true);
🌐
Fellow Tuts
fellowtuts.com › home › php › 3 ways – convert a php object to an array and vice-versa
3 Ways - Convert a PHP Object to an Array and Vice-Versa
December 21, 2018 - So you see that the get_object_vars() function returns an associative array of a defined object accessible in the scope. Also, it doesn’t take non-static properties for the specified object in the account.
🌐
Like Geeks
likegeeks.com › home › web development › cast or convert an array to object using php (hydrator pattern)
Cast or Convert an Array to Object Using PHP (Hydrator Pattern)
To test this converter class, we need to create a class with properties and methods (getters & setters) and see how to convert an array to object using PHP in action. Let’s assume that we have an employee class like this: class Employee { protected $name; protected $phone; protected $email; protected $address; public function getName() { return $this->name; } public function getPhone() { return $this->phone; } public function getEmail() { return $this->email; } public function getAddress() { return $this->address; } public function setName($name) { $this->name = $name; } public function setPhone($phone) { $this->phone = $phone; } public function setEmail($email) { $this->email = $email; } public function setAddress($address) { $this->address = $address; } }
Top answer
1 of 8
157

Here's the really simple example (with no error checking) of how to use ReflectionClass:

function accessProtected($obj, $prop) {
  $reflection = new ReflectionClass($obj);
  $property = $reflection->getProperty($prop);
  $property->setAccessible(true);
  return $property->getValue($obj);
}

I know you said you were limited to 5.2, but that was 2 years ago, 5.5 is the oldest supported version and I'm hoping to help people with modern versions.

2 of 8
73

Object can be typecasted into (associative) array and the protected members have keys prefixed with chr(0).'*'.chr(0) (see @fardelian's comment here). Using this undocummented feature you can write an "exposer":

function getProtectedValue($obj, $name) {
  $array = (array)$obj;
  $prefix = chr(0).'*'.chr(0);
  return $array[$prefix.$name];
}

Alternatively, you can parse the value from serialized string, where (it seems) protected members have the same prefix.

This works in PHP 5.2 without the overhead of ReflectionClass. However, there are reasons why some property is protected and hidden from client code. The reading or writing can make the data inconsistent or the author provides some other way to expose it in effort to make the interface as lean as possible. When there are reasons to read the protected property directly, the then-correct approach was to implement __get() magic method, so always check if there is any and see what it does. This counter intuitive lookup was finally solved in PHP 8.1 with readonly properties.

Since PHP 8.0, there also attributes metadata accessible by ReflectionClass, make sure to check them also before performing attempts to break into protected members. Attributes superseded "Annotations"1, so check them, too.

1: annotations are a very nasty surprise to client coders: they parse comments to add crazy fancy black-box useless confusing functionality, should not be used anymore, but they still exist

🌐
Lobaugh
ben.lobaugh.net › blog › quick-tip-to-access-protected-properties-in-php-object
Quick tip to access protected properties in PHP object | Ben Lobaugh
May 27, 2020 - Generally, this is not something you want to do, however, if you are working with an object you have no control over, it may be necessary. I ran across this while working with an object from an external library. This method works by typecasting the object to an array.
🌐
Exakat
exakat.io › home › mastering the (array) cast operator in php
Mastering the (array) Cast Operator in PHP - Exakat
December 3, 2023 - (array) takes into account the visibility of the properties when converting an object to an array. Protected and private properties are included in the case, yet they get a special treatment. <?php class x extends stdClass { public $public = 1; protected $protected = 2; private $private = 3; } $object = new x; $array = (array) $object; print_r($array); /* Array ( [public] => 1 [*protected] => 2 [xprivate] => 3 ) */
🌐
Kazeno
blag.kazeno.net › development › access-private-protected-properties
Access Private and Protected Properties of Objects in PHP | Thinking around the Box (and other Models)
October 10, 2013 - As you can see PHP sandwiches either an asterisk or the Class name (depending on if the visibility is protected or private, respectively) between two NULL bytes, and prepends this to the property name to form the Array index. You can thus access the hidden properties of an object as follows: class MyExampleClass //example of a class with hidden properties { public $myPublicVar = "I'm public!"; protected $myProtectedVar = "I'm protected!"; private $myPrivateVar = "I'm private!"; } $obj = new MyExampleClass(); $obj_array = (Array)$obj; //cast the object as an Array echo $obj_array['myPublicVar']; //echoes: I'm public!
🌐
No-panic
blog.no-panic.at › 2012 › 01 › 10 › php-converting-object-to-array
PHP converting object to array – blog.no-panic.at
January 10, 2012 - If an object is converted to an array, the result is an array whose elements are the object‘s properties. The keys are the member variable names, with a few notable exceptions: private variables have the class name prepended to the variable name; protected variables have a ‘*’ prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour. Source: http://www.php.net/manual/de/language.types.array.php#language.types.array.casting
🌐
Codegive
codegive.com › blog › php_convert_object_into_array.php
PHP Convert Object to Array: Unlock Seamless Data Manipulation & Avoid Pitfalls (2024 Guide)
For full control over exposing private/protected data, implement a custom public function toArray(): array method within the object's class, where you can explicitly return these properties if desired. Q: Can I convert an array of objects to an array of arrays in PHP?
🌐
GitHub
gist.github.com › victorbstan › 744478
recursively cast a PHP object to array · GitHub
// limit nesting level (for performance and not to go over the maximum) if ( $nestLevel > 15 ) return; // if current member is an object - turn it to an array if( is_object( $obj ) ) $obj = (array) $obj; // if current member is an array - recursively call this function to each of his children if( is_array( $obj ) ) { $return = []; foreach( $obj as $key => $val ) { // correct private and protected key names $aux = explode ( "\0", $key ); $newkey = $aux[ count( $aux ) - 1 ]; $return[ $newkey ] = obj2arr( $val, $nestLevel + 1 ); } } else $return = $obj; // return transformed object return $return
🌐
sqlpey
sqlpey.com › php › effective-php-object-to-associative-array-techniques
Effective PHP Object to Associative Array Conversion Techniques
October 29, 2025 - To reliably access private and protected properties without relying on the complex key-mangling of direct casting, PHP’s Reflection API is necessary. This technique involves iterating through all properties via ReflectionClass, setting accessibility, retrieving the value, and then resetting accessibility for security. /** * Converts object to array using reflection, accessing all properties.
🌐
GUVI
guvi.in › blog › full stack development › how to convert object to array in php (5 easy methods, 2026)
How to Convert Object to Array in PHP (5 Easy Methods, 2026)
September 16, 2026 - The simplest way to convert object to array in PHP is type casting: (array) $object. For nested objects, use json_decode(json_encode($object), true) instead. When you convert object to array using a simple cast, private and protected properties ...