LoginSignup
1
0

More than 5 years have passed since last update.

php7: 関数, メソッドの返り値の型を取得する

Last updated at Posted at 2018-06-15

はじめに

メタプログラミングやフォーマット・仕様自動生成などの時に欲しい関数、メソッドの型を取得します。
ReflectionFunctionAbstract クラスの getReturnType を利用します。
自分用メモ

関数

$functionReflection = new ReflectionFunction('メソッド名');
(string) $functionReflection->getReturnType();

ReflectionFunction 関数用のリフレクションクラスを利用します。 ReflectionFunctionAbstract を継承しているため、getReturnTypeが利用できます。
getReturnType は、タイプが特定できれば ReflectionType 、 それ以外はnullを返します。
組み込みにも利用できますが、nullなことが多いです。

利用例
function foo(): string
{
    return "foo";
}

$functionReflection = new ReflectionFunction('foo');
echo (string) $functionReflection->getReturnType();
// "string"

$functionReflection2 = new ReflectionFunction('array_merge'); // 組み込み
echo (string) $functionReflection2->getReturnType();
// ""

参考 php.net: The ReflectionFunction class および関連項目

クラスメソッド

$methodReflection = new ReflectionMethod('クラスの型', 'メソッド名');
(string) $methodReflection->getReturnType();

メソッドの場合も ReflectionFunctionAbstractを継承しているReflectionMethodを利用すればOKです。

利用例
class Bar()
{
    public bar(): int
    {
        return "1";
    }

    private bar2() // 返り値宣言なし
    {
        return "1";
    }

    public bar3(): Foo
    {
        return new Foo();
    }
}

class Foo()
{
}

$methodReflection = new ReflectionMethod(Bar::class, 'bar');
echo (string) $methodReflection->getReturnType();
// "int"

$methodReflection2 = new ReflectionMethod(Bar::class, 'bar2');
echo (string) $methodReflection2->getReturnType();
// ""

$methodReflection3 = new ReflectionMethod(Bar::class, 'bar3');
echo (string) $methodReflection3->getReturnType();
// "Foo"

参考 php.net: The ReflectionMethod class あたり参照

1
0
0

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
1
0