Thursday, March 17, 2011

object to array of a class with protected variable

Interesting finding for PHP.
By default, if you plan to use get_object_vars to change a class into array, its known that protected and private variable will not be exported to array. Even if you have __sleep method and __get method set to retrieve those variable.

The solution is to put get_object_vars within a method to return get_object_vars($this);

----------------
class A {
public $id = 1;
protected $name = "";

public function __get($name) {
return $this->$name;
}

public function __sleep() {
return array("id", "name");
}

public function toArray() {
return get_object_vars($this);
}
}

$o = new A();
print_r(get_object_vars($o)); //only public variable exposed
print_r($o->toArray()); // all variable are exposed

No comments: