Skip to content

Instantly share code, notes, and snippets.

@artturik
Created August 30, 2016 13:14
Show Gist options
  • Save artturik/b0cc6835dfb95b8e9d8d31408aaab8cc to your computer and use it in GitHub Desktop.
Save artturik/b0cc6835dfb95b8e9d8d31408aaab8cc to your computer and use it in GitHub Desktop.
Dump object to array; convert all object accessible and non-accessible variables to array (public, protected, private, static properties and constants)
<?php
/*
Returns array with object properties, static properties and constants
Can be used for:
* Object to array conversion
* Get all properties (protected and private) list outside the class
* Get protected property value outside the class
* Get private property value outside the class
Please note that constans with same name of property will be overwrited with property value
Please note that this function can not get private varibales from parent class
Returns false if $object param is not object
*/
function dumpObject($object) {
if(!is_object($object)){
return false;
}
$reflection = new \ReflectionObject($object);
$properties = array();
foreach($reflection->getProperties() as $property){
$property->setAccessible(true);
$properties[$property->getName()] = $property->getValue($object);
}
return array_merge((array) $reflection->getConstants(), $properties);
}
<?php
require_once 'DumpObject.php';
class Example {
public $a = 'a';
protected $b = 'b';
private $c = 'c';
public static $d = 'd';
protected static $e = 'e';
private static $f = 'f';
const g = 'g';
}
$test = new Example;
var_dump(dumpObject($example));
/* OUTPUT:
array(7) {
["g"]=>
string(1) "g"
["a"]=>
string(1) "a"
["b"]=>
string(1) "b"
["c"]=>
string(1) "c"
["d"]=>
string(1) "d"
["e"]=>
string(1) "e"
["f"]=>
string(1) "f"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment