Jimmyt1988
Jimmyt1988

Reputation: 21186

Find out the type hinting of a variable - PHP

Is there a way to find out what typehinting has been placed on a variable:

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

I realise in this context this is pointless, but it's to simplify the question.

Edit to help out answering:

Actually the issue is that I am implementing a Factory kind of class. In that factory I need to know what the parameters were of the class that extends the Factory. If it is an IInterface then do a new ThingINeed, but if it was of type IPoopy then I need a new Poopy. kind of thing.

So i am after implementing a factory class that decides what class needs to be instanciated based off of the type hinting declared in the class implementing the factory.

So my case is actually this:

    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();
            }
        }
    }

in reference to : How to implement a factory class using PHP - Dependancy injection

Upvotes: 3

Views: 130

Answers (2)

Alma Do
Alma Do

Reputation: 37365

Your question seems to be odd. It can be resolved with 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);

-but, really, I can't imagine use case for that - since, if it's your function, you are aware of it's arguments definition.

Upvotes: 1

Viridis
Viridis

Reputation: 242

As in ... checking the instance of the parameter?

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

But considering you already assumed your parameter NEEDS to be an instanceOf IInterface, it might be a bit weird to doublecheck if PHP did it's work correctly. Unless i'm missing something.

Upvotes: 1

Related Questions