How to convert an object to an array without a class name prefix in PHP?

How to convert an object to an array without a class name prefix in PHP?

class Teste{ private $a; private $b; function __construct($a, $b) { $this->a = $a; $this->b = $b; } } var_dump((array)(new Teste('foo','bar'))); 

Result:

 array ' Teste a' => string 'foo' (length=3) ' Teste b' => string 'bar' (length=3) 

Expected:

 array ( a => 'foo' b => 'bar' ) 
+4
source share
4 answers

From manual :

If the object is converted to an array, the result is an array whose elements are the properties of the object. Keys are the names of member variables, with a few notable exceptions: integer properties are not available; private variables have a class name appended to the variable name ; protected variables have "*" added to the variable name. These additional values โ€‹โ€‹have zero bytes on both sides . This may lead to unexpected behavior:

Thus, you can work around the problem as follows:

 $temp = (array)(new Teste('foo','bar')); $array = array(); foreach ($temp as $k => $v) { $k = preg_match('/^\x00(?:.*?)\x00(.+)/', $k, $matches) ? $matches[1] : $k; $array[$k] = $v; } var_dump($array); 

It seems strange that there is no way to control / disable this behavior, since there is no risk of collision.

+9
source

The "class name prefix" is part of the (internal) property name. Since you declared private PHP, you need to distinguish something from the $a and $b properties of any subclass.

The easiest way to get around it is not to create them private . Instead, you can declare them as protected .

However, this is not a solution in every case, because something is usually declared as private with intent. I recommend implementing a method that does the conversion for you. This gives you even more control over how the resulting array looks like

 public function toArray() { return array( 'a' => $this->a, 'b' => $this->b ); } 
+3
source

As far as I know, PHP has no easy way to do what you want. Most languages โ€‹โ€‹donโ€™t. You have to look in thought. Take a look at this document: http://www.php.net/manual/en/reflectionclass.getproperties.php

I created a function that should work as expected:

 function objectToArr($obj) { $result = array(); ReflectionClass $cls = new ReflectionClass($obj); $props = $cls->getProperties(); foreach ($props as $prop) { $result[$prop->getName()] = $prop->getValue($obj); } } 
+2
source

You can use Reflection to solve this problem. But, as usual, this is a strong indicator that the design of your class is somewhat broken. But:

 function objectToArray($obj) { // Create a reflection object $refl = new ReflectionClass($obj); // Retrieve the properties and strip the ReflectionProperty objects down // to their values, accessing even private members. return array_map(function($prop) use ($obj) { $prop->setAccessible(true); return $prop->getValue($obj); }, $refl->getProperties()); } // Usage: $arr = objectToArray( new Foo() ); 
+1
source

All Articles