Skip to content

Instantly share code, notes, and snippets.

@bocharsky-bw
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bocharsky-bw/4d95dec6f200d58635c6 to your computer and use it in GitHub Desktop.
Save bocharsky-bw/4d95dec6f200d58635c6 to your computer and use it in GitHub Desktop.
The method convert current object to array
<?php
/**
* Convert current object to array
*/
public function toArray()
{
$data = array();
foreach (get_object_vars($this) as $property => $value) {
if (is_scalar($value) || is_array($value)) {
$data[$property] = $value;
} elseif (is_object($value)) {
if ($value instanceof \DateTime) {
$data[$property] = $value->getTimestamp();
} elseif ($value instanceof Image) {
$data[$property] = $value ? $value->getWebPath() : null;
} else {
$method = 'toArray';
if (method_exists($value, $method)) {
$data[$property] = $value->$method();
}
}
}
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment