找出一个变量的类型提示-PHP


Find out the type hinting of a variable - PHP

有没有一种方法可以找出变量上的类型提示:

...function( IInterface $blah )
{
    if( gettypehint( $blah ) == IInterface )
    {
        echo "yay";
    }
}

我意识到在这种情况下这是毫无意义的,但这是为了简化问题。

编辑以帮助回答:

事实上,问题是我正在实现一个工厂类。在那个工厂里,我需要知道扩展工厂的类的参数是什么。如果是IInterface,那么做一个新的ThingINeed,但如果是IPoopy类型,那么我需要一个新Poopy。诸如此类的事情。

因此,我正在实现一个工厂类,该类根据实现工厂的类中声明的类型提示来决定需要安装哪个类。

所以我的情况实际上是这样的:

    public function AddBinding( $interface, $concrete )
    {
        $calledClass = get_called_class();
        $class = new 'ReflectionClass( $calledClass );
        $method = $class->getMethod( "__construct" );
        $params = $method->getParameters();
        foreach( $params as $param )
        {
            if ( $param instanceof $interface )
            {
                return new $concrete();
            }
        }
    }

参考:如何使用PHP实现工厂类-依赖注入

As in。。。检查参数的实例?

instanceof:http://www.php.net/manual/en/internals2.opcodes.instanceof.php

但考虑到您已经假设您的参数需要是IInterface的instanceOf,仔细检查PHP是否正确工作可能会有点奇怪。除非我错过了什么。

你的问题似乎很奇怪。可通过ReflectionFunction API:解决

function foo(StdClass $arg)
{
   $function = new ReflectionFunction(__FUNCTION__);
   $args     = array_map(function($item)
   {
      return $item->getClass()->getName();
   }, $function->getParameters());
   //var_dump($args);
   //so, if ($args[0]=='SomeNeededClass') { ... }
}
$obj = new StdClass();
foo($obj);

-但是,实际上,我无法想象它的用例——因为,如果它是你的函数,你知道它的参数定义。