Skip to content

Instantly share code, notes, and snippets.

@auxiliaire
Created April 7, 2021 19:45
Show Gist options
  • Select an option

  • Save auxiliaire/8ef60719c071796f630ef19c086bc9d1 to your computer and use it in GitHub Desktop.

Select an option

Save auxiliaire/8ef60719c071796f630ef19c086bc9d1 to your computer and use it in GitHub Desktop.
Implement `prop` for objects in PHP
function _getProp(string $prop, object $obj) {
$r = new ReflectionClass($obj);
$hasProp = $r->hasProperty($prop);
$getter = 'get' . ucfirst($prop);
$hasGetter = $r->hasMethod($getter);
return match (true) {
$hasProp && $r->getProperty($prop)->isPublic() => $obj->$prop,
$hasGetter && $r->getMethod($getter)->isPublic() => $obj->$getter(),
default => null
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment