Created
April 7, 2021 19:45
-
-
Save auxiliaire/8ef60719c071796f630ef19c086bc9d1 to your computer and use it in GitHub Desktop.
Implement `prop` for objects in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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