title: PHP dynamic return type hinting
body: <p>Suppose I have the following PHP function:</p>
  
  <pre><code>/**
   * @param string $className
   * @param array $parameters
   * @return mixed
   */
  function getFirstObject($className, $parameters) {
      // This uses a Doctrine DQl builder, but it could easily replaced
      // by something else. The point is, that this function can return
      // instances of many different classes, that do not necessarily
      // have common signatures.
      $builder = createQueryBuilder()
          -&gt;select('obj')
          -&gt;from($className, 'obj');
      addParamClausesToBuilder($builder, $parameters, 'obj');
      $objects = $builder
          -&gt;getQuery()
          -&gt;getResult();
      return empty($objects) ? null : array_pop($objects);
  }
  </code></pre>
  
  <p>Basically, the function always returns either an instance of the class specified with the <code>$className</code> parameter or <code>null</code>, if something went wrong. The only catch is, that I do not know the full list of classes this function can return. (at compile time)</p>
  
  <p><strong>Is it possible to get type hinting for the return type of this kind of function?</strong></p>
  
  <p>In Java, I would simply use generics to imply the return type:</p>
  
  <pre><code>static &lt;T&gt; T getOneObject(Class&lt;? extends T&gt; clazz, ParameterStorage parameters) {
      ...
  }
  </code></pre>
  
  <p>I am aware of the manual type hinting, like</p>
  
  <pre><code>/** @var Foo $foo */
  $foo = getOneObject('Foo', $params);
  </code></pre>
  
  <p>but I would like to have a solution that does not require this boilerplate line.</p>
  
  <p>To elaborate: I am trying to write a wrapper around Doctrine, so that I can easily get the model entities that I want, while encapsulating all the specific usage of the ORM system. I am using PhpStorm.</p>
  
  <p>** edited function to reflect my intended usage. I originally wanted to keep it clean of any specific use case to not bloat the question. Also note, that the actual wrapper is more complex, since I also incorporate model-specific implicit object relations and joins ect.</p>