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 | |
// 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