LoginSignup
6
1

More than 5 years have passed since last update.

PHPで型クラスを書くとどうなるか考えてみた

Posted at

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

6
1
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1