PHPで型クラスを表現するとどうなるか考えてみた。PHPは型宣言できるものの、ジェネリクスが無かったり、型の整合性チェックができるコンパイルの仕組みも無いので、型クラスを用いてもScalaのようなメリットはないが、凝集性の高い設計パターンとしての有益性はあるかもしれない。
<?php
/**
* 型クラス
* @template T
*/
interface Show
{
/**
* @param T $value
*/
public function show($f): string;
}
/**
* @inherits Show<string>
*/
class StringShow implements Show
{
public function show($f): string
{
assert(is_string($f));
return $f;
}
}
/**
* @inherits Show<bool>
*/
class BoolShow implements Show
{
public function show($f): string
{
assert(is_bool($f));
return $f ? 'true' : 'false';
}
}
/**
* @template T
* @inherits Show<T>
* @return Closure(T):string
*/
function quote(Show $show) {
/**
* @param T $f
*/
return function ($f) use ($show) {
return '"' . $show->show($f) . '"';
};
}
echo quote(new StringShow())('hello'), PHP_EOL; //=> "hello"
echo quote(new BoolShow())(true), PHP_EOL; //=> "true"
echo quote(new StringShow())(1), PHP_EOL; // assertion failure