class aClass { protected $protected_property = 'protected_value'; private $private_property = 'private_value'; public $public_property = 'public_value'; } $an_object = new aClass; var_dump($an_object); // object(aClass)#1 (3) { // ["protected_property":protected]=> // string(15) "protected_value" // ["private_property":"aClass":private]=> // string(13) "private_value" // ["public_property"]=> // string(12) "public_value" // }
$an_array = array(); $reflection = new ReflectionClass($an_object); $properties = $reflection->getProperties(); foreach ($properties as $property) { $property->setAccessible(true); $an_array[$property->getName()] = $property->getValue($an_object); if (!$property->isPublic()) $property->setAccessible(false); } var_dump($an_array); // array(3) { // ["protected_property"]=> // string(15) "protected_value" // ["private_property"]=> // string(13) "private_value" // ["public_property"]=> // string(12) "public_value" // }
$an_array = (array) $an_object; var_dump($an_array); // array(3) { // [" * protected_property"]=> // string(15) "protected_value" // [" aClass private_property"]=> // string(13) "private_value" // ["public_property"]=> // string(12) "public_value" // }
$key = ($key{0} === "\0") ? substr($key, strpos($key, "\0", 1) + 1) : $key;
$an_another_object = (object) $an_array; var_dump($an_another_object); // object(stdClass)#6 (3) { // ["protected_property":protected]=> // string(15) "protected_value" // ["private_property":"aClass":private]=> // string(13) "private_value" // ["public_property"]=> // string(12) "public_value" // }
$an_array = array(); reset($an_object); while (list($key, $val) = each($an_object)) $an_array[$key] = $val; var_dump($an_array); // array(3) { // [" * protected_property"]=> // string(15) "protected_value" // [" aClass private_property"]=> // string(13) "private_value" // ["public_property"]=> // string(12) "public_value" // }
$an_array["\0aClass\0private_property"] = 'new_private_value'; array_walk($an_object, function(&$val, $key, $array){$val = $array[$key];}, $an_array); var_dump($an_object); // object(aClass)#1 (3) { // ["protected_property":protected]=> // string(15) "protected_value" // ["private_property":"aClass":private]=> // string(17) "new_private_value" // ["public_property"]=> // string(12) "public_value" // }
Source: https://habr.com/ru/post/138102/