Skip to content

Instantly share code, notes, and snippets.

@Tiriel
Last active September 15, 2017 21:42
Show Gist options
  • Save Tiriel/c81c6392080de30a0a5413e213dacdce to your computer and use it in GitHub Desktop.
Save Tiriel/c81c6392080de30a0a5413e213dacdce to your computer and use it in GitHub Desktop.
Universal __set and __get methods
<?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