Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk mindplay-dk/reflection-pseudo.php Secret
Last active Feb 28, 2016

Embed
What would you like to do?
<?php
// pseudo-code:
class ReflectionClass
{
// ...
/**
* @return ReflectionTypeParam[]
*/
public function getTypeParams()
{
// ...
}
/**
* @return bool
*/
public function isGeneric()
{
return count($this->getTemplates()) > 0;
}
}
/**
* This class represents a template type (type parameter) of a generic class
*/
class ReflectionTypeParam
{
/**
* @var ReflectionClass owner class reference
*/
protected $class;
/**
* @var string template name, e.g. "T"
*/
protected $name;
public function __construct(ReflectionClass $class, $name)
{
$this->class = $class;
$this->name = $name;
}
/**
* @return ReflectionTypeArg
*/
public function getTypeArg($object)
{
// return
}
public function __toString() {
return $this->name;
}
}
/**
* This class represents a type provided as a type argument
* for an individual template type of a generic object
*/
class ReflectionTypeArg
{
/**
* @return bool
*/
public function check($value)
{
// return true, if the given value passes a type-check for this type-argument
}
/**
* @return bool
*/
public function isBuiltIn()
{
// return true, if the type being checked is a built-in type (int, bool, string, etc.)
}
public function __toString()
{
// return e.g. "User" or "int" etc.
}
}
// usage:
class Box<T> {
/**
* @var T
*/
private $value;
public function get() : T {
return $this->value;
}
public function set(T $value) {
$this->value = $value;
}
}
class Hat {}
$box = new Box<Hat>();
$box_class = new ReflectionClass("Box");
var_dump($box_class->getTypeParams()[0]->getTypeArg($box)->__toString()); // "Hat"
var_dump($box_class->getTypeParams()[0]->getTypeArg($box)->check(new Hat())); // true
// case with structured type argument:
$boxed_box = new Box<Box<Hat>>();
var_dump($box_class->getTypeParams()[0]->getTypeArg($boxed_box)->__toString()); // "Box<Hat>"
var_dump($box_class->getTypeParams()[0]->getTypeArg($box)->check(new Box<Hat>())); // true
// case with type argument defined via extends clause:
class HatBox extends Box<Hat> {}
$hat_box = new HatBox();
var_dump($box_class->getTypeParams()[0]->getTypeArg($hat_box)->__toString()); // "Hat"
var_dump($box_class->getTypeParams()[0]->getTypeArg($hat_box)->check(new Hat())); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.