2016-03-28 3 views
3

私は変数$barを取得しようとしています。リフレクトされたクラスメソッドでパラメータタイプを取得する方法は?

<?php 
class Foo 
{ 
    public function test(stdClass $bar, array $foo) 
    { 

    } 
} 

$reflect = new ReflectionClass('Foo'); 
foreach ($reflect->getMethods() as $method) { 
    foreach ($method->getParameters() as $num => $parameter) { 
     var_dump($parameter->getType()); 
    } 
} 

私はstdClassを期待するが、私は間違っている可能性が何

Call to undefined method ReflectionParameter::getType() 

を取得しますか?またはいくつかの他の方法はありますか?...

$ php -v 
PHP 5.4.41 (cli) (built: May 14 2015 02:34:29) 
Copyright (c) 1997-2014 The PHP Group 
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies 

UPD1 配列が同様に入力することが動作するはずです。

+3

[のgetType()](http://php.net/manual/en/reflectionparameter.gettype.php)は、PHP 7. –

+0

アップで提供されています...これをありがとう注意。 – Kirby

答えて

2

それはすでに PHP Reflection - Get Method Parameter Type As String

に追加同様の質問のように私はそれがすべてのケースのために働く私の解決策を書いたになります。

/** 
* @param ReflectionParameter $parameter 
* @return string|null 
*/ 
function getParameterType(ReflectionParameter $parameter) 
{ 
    $export = ReflectionParameter::export(
     array(
      $parameter->getDeclaringClass()->name, 
      $parameter->getDeclaringFunction()->name 
     ), 
     $parameter->name, 
     true 
    ); 
    return preg_match('/[>] ([A-z]+) /', $export, $matches) 
     ? $matches[1] : null; 
} 
3

あなただけのクラスをほのめかし入力している場合は、あなたがある->getClass()を使用することができますPHP 5および7でサポートされています。

<?php 

class MyClass { 

} 

class Foo 
{ 
    public function test(stdClass $bar) 
    { 

    } 

    public function another_test(array $arr) { 

    } 

    public function final_test(MyClass $var) { 

    } 
} 

$reflect = new ReflectionClass('Foo'); 
foreach ($reflect->getMethods() as $method) { 
    foreach ($method->getParameters() as $num => $parameter) { 
     var_dump($parameter->getClass()); 
    } 
} 

私がクラスと言う理由は、配列上にあるためですurn NULL。

Output

object(ReflectionClass)#6 (1) { 
    ["name"]=> 
    string(8) "stdClass" 
} 
NULL 
object(ReflectionClass)#6 (1) { 
    ["name"]=> 
    string(7) "MyClass" 
} 
+0

うん、それは動作します。ありがとう!だから、 '$ parameter-> getClass()? $ parameter-> getClass() - >名前:ヌル; '私はなぜそれに気付かなかったのか分からない。)それは遅すぎると思われる、午後9時。 :) – Kirby

+0

ねえ!この場合、三元はうまくいく。 –

+0

うん、それは配列を働かない... :( – Kirby

関連する問題