// start
class MyClass {
public $var1 = 1;
public $var2 = 2;
public static $var3 = 3;
protected $var4 = 4;
private $var5 = 5;
public function toArray() {
return (array) get_object_vars($this);
}
}
function toArray($object) {
//$reflectionClass = new ReflectionClass(get_class($object));
$reflectionClass = new ReflectionObject($object);
$array = [];
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$array[$property->getName()] = $property->getValue($object);
$property->setAccessible(false);
}
return $array;
}
$object = new MyClass();
$array = toArray($object);
$array2 = $object->toArray();
print_r($array2); // Inaccessible NO static
print_r($array); // Inaccessible and static
$obArray = [];
foreach($object as $ob){
$obArray[] = $ob;
}
print_r($obArray); // public only
Array
(
[var1] => 1
[var2] => 2
[var4] => 4
[var5] => 5
)
Array
(
[var1] => 1
[var2] => 2
[var3] => 3
[var4] => 4
[var5] => 5
)
Array
(
[0] => 1
[1] => 2
)