Last active
September 15, 2017 21:42
-
-
Save Tiriel/c81c6392080de30a0a5413e213dacdce to your computer and use it in GitHub Desktop.
Universal __set and __get methods
This file contains 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
<?php | |
/** | |
* @param $name | |
* @param $value | |
* @return $this | |
*/ | |
function __set($name, $value) | |
{ | |
$reflected = new \ReflectionClass($this); | |
$property = $reflected->getProperty($name); | |
// Retrieving type hint from DocBlock | |
preg_match('/@var\s+([^\s]+)/', $property->getDocComment(), $matches); | |
list(, $propType) = $matches; | |
// Retriving argument type | |
$valueType = gettype($value); | |
// Integrity check | |
$propType = str_replace(array('double', 'boolean', 'int'), array('float', 'bool', 'integer'), $propType); | |
$valueType = str_replace(array('double', 'boolean'), array('float', 'bool'), $valueType); | |
// Comparing | |
if ($propType !== $valueType) { | |
throw new \InvalidArgumentException("Invalid type provided for $name (expected : $propType , got $valueType)."); | |
} | |
$this->$name = $value; | |
return $this; | |
} | |
/** | |
* @param $name | |
* @return mixed | |
*/ | |
function __get($name) | |
{ | |
return $this->$name; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment