- array_keys: documentation ( source)
- get_object_vars: documentation ( source)
<?php
function x($o) { return get_object_vars($o);}
class A {
public $a;
public $b;
private $c;
protected static $columnRegistry = array();
protected $columns = array();
public function __construct($a, $b, $c) {
$this->a = $a;
$this->b = $b;
$this->c = $c;
$this->setupColumns();
}
public function toArray() {
$ret = [];
foreach ($this->columns as $column) {
$ret[$column] = $this->$column;
}
return $ret;
}
protected function setupColumns()
{
$class = get_class($this);
// Define columns for current row
if (!array_key_exists($class, self::$columnRegistry)) {
$this->columns = array_keys(x($this));
self::$columnRegistry[$class] = $this->columns;
} else {
$this->columns = self::$columnRegistry[$class];
}
}
}
$expected = [
'a' => 1,
'b' => 2,
];
$numReps = 100000;
for($i = 0; $i < $numReps; $i++) {
$o = new A(1, 2, 3);
$res = $o->toArray();
if ($res !== $expected) {
throw new Exception("Not same");
}
}
echo "OK";